Trying to append a text file using java printwriters - java

So I have a few other classes like this one, I call the method in using an object in the run file. I want to write every output of every class into the same text file. However at the moment only one output is being saved to the text file, as it is overwriting each time, how do I do this using a print writer seen below?
Any guidance is much appreciated!
Class:
package cw;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Scanner;
import javax.swing.JFileChooser;
import java.io.IOException;
public class LineCounter {
public static void TotalLines() throws IOException {
Scanner sc = new Scanner(TextAnalyser.class.getResourceAsStream("test.txt"));
PrintWriter out = new PrintWriter(new FileWriter("C:\\Users\\Sam\\Desktop\\Report.txt"));
int linetotal = 0;
while (sc.hasNextLine()) {
sc.nextLine();
linetotal++;
}
out.println("The total number of lines in the file = " + linetotal);
out.close();
System.out.println("The total number of lines in the file = " + linetotal);
}
}
Run File:
package cw;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Scanner;
import javax.swing.JFileChooser;
import java.io.IOException;
public class TextAnalyser {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(TextAnalyser.class.getResourceAsStream("test.txt"));
LineCounter Lineobject = new LineCounter();
WordCounter Wordobject = new WordCounter();
NumberCounter Numberobject = new NumberCounter();
DigitCounter Digitobject = new DigitCounter();
SpaceCounter Spaceobject = new SpaceCounter();
NumberAverage Noavgobject = new NumberAverage();
WordAverage Wordavgobject = new WordAverage();
Palindromes Palindromeobject = new Palindromes();
VowelCounter Vowelobject = new VowelCounter();
ConsonantCounter Consonantobject = new ConsonantCounter();
WordOccurenceTotal RepeatsObject = new WordOccurenceTotal();
Lineobject.TotalLines();
Wordobject.TotalWords();
Numberobject.TotalNumbers();
Digitobject.TotalDigits();
Spaceobject.TotalSpaces();
Noavgobject.NumberAverage();
Wordavgobject.WordAverage();
Vowelobject.TotalVowels();
Consonantobject.TotalConsonant();
Palindromeobject.TotalPalindromes();
//RepeatsObject.TotalRepeats();
}
}

You want to use the second argument of the FileWriter constructor to set the append mode:
new FileWriter("name_of_your_file.txt", true);
instead of:
new FileWriter("name_of_your_file.txt");

Related

Frame extractor

So, I've been trying to create a frame extractor but, obviously, it doesn't work. Here's what it look likes
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Scanner;
import java.sql.Time;
import javax.imageio.ImageIO;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;
public class FrameExtract {
public static void main(String []args) throws Exception
{
System.out.println("Please enter the file name and path");
Scanner filepath = new Scanner(System.in);
String filename = filepath.nextLine();
File myObj = new File(filename);
System.out.println("Please enter the precise time of the frame you want to extract");
Scanner timeex = new Scanner(System.in);
Long timetoex = timeex.nextLong();
Time timestamp = new Time(timetoex);
FFmpegFrameGrabber frameGrabber = new FFmpegFrameGrabber(myObj.getAbsoluteFile());
frameGrabber.start();
Frame f;
try {
Java2DFrameConverter c = new Java2DFrameConverter();
f = frameGrabber.grab();
BufferedImage bi = c.convert(f);
ImageIO.write(bi,"png", new File("D:\\img.png"));
frameGrabber.stop();
} catch (Exception e) {
e.printStackTrace();
}
}
}
and the exceptions show this:
java.util.Scanner.throwFor(Scanner.java:864)
java.util.Scanner.next(Scanner.java:1485)
java.util.Scanner.nextLong(Scanner.java:2222)
java.util.Scanner.nextLong(Scanner.java:2182)
Eng.F.FrameExtract.main(FrameExtract.java:22)
I know there is problems like the code doesn't use the time properly, or even at all

Java issue with reading a text file into an ArrayList

I have created a program that is supposed to read a text file for Integers and put them into an Arraylist, and then there are a bunch of methods to act on it. but, after some trouble shooting I am noticing that my program won't pull the integers from the text file in. Could anyone point me in the right direction?
package project1;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
import java.lang.System;
public class Main {
public static void main(String[] Args) {
Main mainObject = new Main();
mainObject.run();
}
public void run() {
**ArrayList<Integer> list = new ArrayList<>();
String fileName = "p01-in.txt";
Scanner in = new Scanner(fileName);
while (in.hasNextInt()) {
list.add(in.nextInt());
int line = in.nextInt();
System.out.println("%s %n" + line);
}
in.close();**
ArrayList<Integer> listRunsUpCount = new ArrayList<>();
ArrayList<Integer> listRunsDnCount = new ArrayList<>();
Main findRuns = new Main();
listRunsUpCount = findRuns.FindRuns(list, 0);
listRunsDnCount = findRuns.FindRuns(list, 1);
ArrayList<Integer> listRunsCount = new ArrayList<>();
Main mergeRuns = new Main();
listRunsCount = mergeRuns.MergeRuns(listRunsUpCount,
listRunsDnCount);
Main Output = new Main();
Output.Output("p01-runs.txt", listRunsCount);
}
You can use BufferedReader to read file content line by line.
try {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line=reader.readLine();
while (line != null) {
line = reader.readLine();
list.add(Integer.parseInt(line.trim()));
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}

Weka API on Eclipse Java

i want to classify string type dataset with test and training labeled.
i use this code in Eclipse java while i import Weka.jar file already
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import weka.classifiers.functions.SMO;
import weka.filters.unsupervised.attribute.StringToWordVector;
import weka.core.Instances;
public class Classify {
public static void main(String[] args) throws Exception {
//load data set for training//
BufferedReader breader = null;
breader = new BufferedReader(new FileReader("C:/nfrtraining.arff"));
Instances train = new Instances(breader);
train.setClassIndex(train.numAttributes() - 1);
//test data set for testing//
breader = new BufferedReader(new FileReader("C:/nfrtesting1.arff"));
Instances test = new Instances(breader);
test.setClassIndex(test.numAttributes() - 1);
// classifier applied
SMO svm = new SMO();
svm.buildClassifier(train);
System.out.println(svm.getCapabilities().toString());
Instances labeled = new Instances(test);
//for label instances
for (int i = 0; i < test.numInstances(); i++) {
double clsLabel = svm.classifyInstance(test.instance(i));
labeled.instance(i).setClassValue(clsLabel);
}
//save labeled data
BufferedWriter writer = new BufferedWriter(
new FileWriter("c:/labelled.arrf"));
writer.write(labeled.toString());
}
}
when i run this code an error is displayed like:
at weka.core.Capabilities.test(Capabilities.java:1277)
at weka.core.Capabilities.test(Capabilities.java:1208)
at weka.core.Capabilities.testWithFail(Capabilities.java:1506)
at weka.classifiers.functions.SMO.buildClassifier(SMO.java:1330)
at Classify.main(Classify.java:30)
this error is in scr file i am unable to eid. please someone help to resolve this problem

Using Java Scanner class ,how do I get the most recent number which comes after specific String?

I have text log files which follow this format:
18:27:08.231 [main] DEBUG sample_client - This is a DEBUG message,
line 39 Location 7 18:27:09.231 [main] DEBUG sample_client - This is
anr DEBUG message, line 39 Location 17 18:27:10.231 [main] DEBUG
sample_client - This is a DEBUG message, line 56 Location 23
I would like to obtain the most recent integer, that comes after the String "Location" - here it is 23.
The following is my Scanner class so far :
import org.apache.logging.log4j.flume; */
// import org.slf4j.Logger;
// import org.slf4j.LoggerFactory;
import java.sql.Timestamp;
import java.util.Date;
import java.util.*;
import java.io.*;
import java.net.*;
public class ScannerTest { /* BEGINBRAC */
public static void main(String[] args) throws IOException {
int mostRecentLocation = 0;
Scanner scanner = new Scanner ("LogbackTutorialError.txt");
while (scanner.hasNextLine() ) {
final String lineFromFile = scanner.nextLine();
if(lineFromFile.contains("Location")){
System.out.print("the location is " + mostRecentLocation );
}
}
}
}// end class ScannerTest
How do I go about getting the most recent number after Location ?
You could do something with String.substring(int) to remove everything from Location on. Something like,
if (lineFromFile.startsWith("Location")) {
int mostRecentLocation = Integer.parseInt(lineFromFile
.substring(1 + "Location".length()).trim());
System.out.println("the location is " + mostRecentLocation);
}
The following code shows how to create it.
import java.sql.Timestamp;
import java.util.Date;
import java.util.*;
import java.io.*;
import java.net.*;
public class ScannerTest {
public static void main(String[] args) throws FileNotFoundException {
int mostRecentLocation = 0;
File newFile = new File("LogbackTutorialError.log");
Scanner scanner = new Scanner (newFile);
int result = 0;
while (scanner.hasNextLine() ) {
String lineFromFile = scanner.nextLine();
Scanner lineScanner = new Scanner(lineFromFile);
if(lineScanner.findInLine("Location") != null){
result = lineScanner.nextInt() ;
mostRecentLocation = result;
}
}
System.out.println(" The location is : " + result );
}
}// end class ScannerTest

Getting arrayoutofbond error while running java code

I am getting arrayoutofbond error while running below given code,
sometime it is running as expected and sometime it is giving error.
Could anyone help me where I am wrong.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
public class getFileContent{
public void listFiles() throws IOException, InterruptedException{
File directory = new File("C:\\ScriptLogFile\\");
File[] myarray;
myarray=directory.listFiles();
int i=0;
ArrayList<String> arrayList = new ArrayList<String>();
SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy_hhmmss");
Date curDate = new Date();
String strDate = sdf.format(curDate);
String fileName = strDate;
File file = new File("C:\\ExcelReport_"+fileName+".csv");
FileWriter fileWritter = new FileWriter(file, true);
BufferedWriter bwr = new BufferedWriter(fileWritter);
String filename = null;
try {
for (int j = 0; j < myarray.length; j++)
{
File path=myarray[j];
FileInputStream fis = new FileInputStream (path);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
if(path.isFile()){
if(path.getName().endsWith(".csv")){
filename = path.getName();
String line;
bwr.write(filename+",");
while ((line = br.readLine()) != null) {
if(line.contains("-")){
String[] part = line.split("-");
arrayList.add(part[1]);
bwr.write(arrayList.get(i)+",");
i++;
}
else{
}
}
bwr.write("\r\n");
}
}
}
}catch (FileNotFoundException e) {
e.printStackTrace();
}
bwr.close();
}
public static void main(String[] args) throws IOException, InterruptedException {
getFileContent gfc = new getFileContent();
gfc.listFiles();
}
}
We need a stack trace to see where the exception is raised. However you seem to be making assumptions about the length of part[]. Remember arrays are 0-indexed, the first entry would be at index 0 i.e. part[0]. Even then, in general there really needn't be many entries at all: "xyz".split("-") is an array of length 1 whose only element, "xyz", is at index 0.

Categories

Resources