Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java FileWriter with append mode

I'm currently using FileWriter to create and write to a file. Is there any way that I can write to the same file every time without deleting the contents in there?

   fout = new FileWriter(     "Distribution_" + Double.toString(_lowerBound) + "_" + Double.toString(_highBound) + ".txt");     fileout = new PrintWriter(fout,true); fileout.print(now.getTime().toString() + ", " + weight + ","+ count +"\n");     fileout.close(); 
like image 200
Progress Programmer Avatar asked Aug 03 '09 23:08

Progress Programmer


People also ask

How do you make a FileWriter object in append mode?

From the Javadoc, you can use the constructor to specify whether you want to append or not. 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.

Does FileWriter write append?

FileWriter class is used for writing streams of characters. FileWriter takes an optional second parameter: append . If set to true, then the data will be written to the end of the file. This example appends data to a file with FileWriter .

Does FileWriter append or overwrite?

When you create a Java FileWriter you can decide if you want to overwrite any existing file with the same name, or if you want to append to any existing file. You decide that by choosing what FileWriter constructor you use.

How do I append to an output stream?

Using FileOutputStream FileOutputStream is meant for writing streams of raw bytes such as image data. For writing streams of characters, consider using FileWriter . To append content to an existing file, open FileOutputStream in append mode by passing the second argument as true .


1 Answers

Pass true as a second argument to FileWriter to turn on "append" mode.

fout = new FileWriter("filename.txt", true); 

FileWriter usage reference

like image 87
Amber Avatar answered Sep 24 '22 15:09

Amber