not writing line by line - java

private static void displaytoFile(int trial, int count) {
// TODO Auto-generated method stub
String answer;
try{
// Create file
FileWriter fstream = new FileWriter(outputfile);
BufferedWriter out = new BufferedWriter(fstream);
answer = "Case #"+trial+": "+count;
out.write(answer);
out.newLine();
//Close the output stream
out.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
The displaytoFile() method is called in a loop in my project but i am not able to write line by line into the file.It only writes the last line ie the parameters passed during the last iteration.I tested in console and the other code is ok,it displays all but this code snippet seems to have some problem as it seems it overwrites the previous values.How can i get to write to file line by line?

Use the FileWriter(String, boolean) constructor in order to append the input instead of rewriting the entire file:
FileWriter fstream = new FileWriter(outputfile, true);

FileWriter fstream = new FileWriter(outputfile);
BufferedWriter out = new BufferedWriter(fstream);
answer = "Case #"+trial+": "+count;
out.write(answer);
out.newLine();
//Close the output stream
out.close();
has problem. This is because inside each iteration of your loop, you clear the file then write current line into it. you should open the file before the loop and close it after the loop. Or making sure that you are append to the file, not first clear then write, like what you did now.

You have to indicate that you want to append to the file
See method documentation here

Related

Multiple Lines into One Text File? - Java

How can I save multiple lines into One Text File?
I want to print "New Line" in the same Text File every time the code is executed.
try {
FileWriter fw = new FileWriter("Test.txt");
PrintWriter pw = new PrintWriter(fw);
pw.println("New Line");
pw.close();
}
catch (IOException e)
{
System.out.println("Error!");
}
I'm able to create a new file but can't create a new line every time the code is executed.
Pass true as a second argument to FileWriter to turn on "append" mode.
FileWriter fw = new FileWriter("filename.txt", true);
That will make your file to open in the append mode, which means, your result will be appended to the end of the file each time you'll write to the file. You can also write '\n' after each content writing so that it will inserts a new line there.
You are creating a new line every time it is run, the problem is that you are truncating the file when you open it. I suggest you append to the file each time.
try (FileWriter fw = new FileWriter("Test.txt", true); // true for append
PrintWriter pw = new PrintWriter(fw)) {
pw.println("New Line");
} // try-with-resource closes everything.
Note: openning and closing a file for each line is expensive, If you do this a lot I suggest leaving the file open and flushing the output each time.
You are doing this:
FileWriter fw = new FileWriter("Test.txt");
which is overwriting the file every time you execute that line...
BUT you need instead to append the data to the file
FileWriter fw = new FileWriter("Test.txt", true);
take a look at the constructor in the doc
You need to open the file in append mode. You can do that as follows:
FileWriter fw = new FileWriter("Test.txt", true);
Here is the documentation for the same.

File.delete() fails

This is my code to delete a line of text from a text file. I have an add function which appends a line of text to the text file. When I delete every line of text from the text file and add back some lines of text using my add function, the delete() always fails. I checked that the file exists, and have closed everything I could and thus not sure why the delete would fail. How do I proceed to debug this problem without knowing why the delete fails?
{
int currLineNum = 1;
File temp = new File("temp.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
FileWriter fileWriter = new FileWriter(temp, true);
BufferedWriter buffer = new BufferedWriter(fileWriter);
PrintWriter printWriter = new PrintWriter(buffer);
String currentLine;
// .. loop omitted ..
reader.close();
printWriter.close();
buffer.close();
fileWriter.close();
if(inputFile.delete()) //code fails here
System.out.println("DELETED");
else
System.out.println("FAILED");
if(temp.renameTo(inputFile))
System.out.println("DONE");
else
System.out.println("NOT DONE");
}

BufferedWriter newLine method not found

I'm trying to get a BufferedWriter to print several Strings, each on a different Line in a text file. I'm trying to use out.newLine() to set a new line for the next string, but I'm getting an error message of cannot find symbol - method newLine()
This is the code I am trying to use:
Writer out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(start+"2"+dest+".txt"), "utf-8")); // create output file from start names
out.write(outputOne);//Write Line 1
out.newLine();
out.write(outputTwo); //Write Line 2
out.newLine();
out.write(outputThree); //Write Line 3
out.newLine();
out.write(outputFour); //Write Line 4
out.close();
} catch (IOException ex) { //Handle Errors
System.err.println("Error in BufferedWriter, IOException");
} finally {
try {out.close();}
catch(Exception ex) {}
}
Declare your variable with a type of BufferedWriter. Writer does not have a newLine() method.
BufferedWriter out;
Methods are resolved, at compile time, based on the declared/static type of the variable (or expression) they are invoked on.
Alternatively, cast the variable
((BufferedWriter)out).write(outputFour);
but this is long.
Consider using try-with-resources.

How to add a line in a text file without overwriting it (JAVA)?

My data is stored in an ArrayList whose size increases during program execution.
I managed to save all the data whenever the size increases, but this brings me to overwrite the data already stored.
The solution is to go directly to the bottom line and insert the contents of the last cell of ArrayList. Unfortunately I do not know how to implement it.
Thank you for helping me to do this.
Below is the method I used.
private void SaveLocationData(){
try {
FileOutputStream output = openFileOutput("latlngpoints.txt",Context.MODE_PRIVATE);
DataOutputStream dout = new DataOutputStream(output);
dout.writeInt(LocationList.size());
for (Location location : LocationList) {
dout.writeUTF(location.getLatitude() + "," + location.getLongitude());
}
dout.flush(); // Flush stream ...
dout.close(); // ... and close.
} catch (IOException exc) {
exc.printStackTrace();
}
}
Use MODE_APPEND:
FileOutputStream output = openFileOutput("latlngpoints.txt",Context.MODE_APPEND);
From the doc:
File creation mode: for use with openFileOutput(String, int), if the
file already exists then write data to the end of the existing file
instead of erasing it.
You can try this too
FileWriter fstream = new FileWriter("x.txt",true); //this will allow to append
BufferedWriter fbw = new BufferedWriter(fstream);
fbw.write("append txt...");
fbw.newLine();
fbw.close();

How to add content to files using Java

I have a result being entered into a file. This result is being done on a loop. So, every time a new result comes, it has to be appended into a file, but it is being overwritten. What should I use in order to append my results into a single file?
Try
BufferedWriter out = null;
try {
out = new BufferedWriter(new FileWriter("filename", true));
out.write("aString");
}
catch (IOException e) {
// handle exception
}
finally{
if(out != null){
try{
out.close();
}
catch(IOException e){
// handle exception
}
}
}
According to the API,
Constructs a FileWriter object given a
File object. If the second argument is
true, then bytes will be written to
the end of the file rather than the
beginning.
here is the basic snippet
FileWriter fstream = new FileWriter("out.txt",true);
BufferedWriter out = new BufferedWriter(fstream);
out.write("Hello Java 1");
out.write("Hello Java 2");
See Also
FileWritter - Javadoc
You should either keep the file open (sometimes it better, but usually not...) or open the output stream in append mode:
OutputStream os = new FileOutputStream(file, true);

Categories

Resources