46

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();
Hack-R
  • 22,422
  • 14
  • 75
  • 131
Progress Programmer
  • 7,076
  • 14
  • 49
  • 54

4 Answers4

118

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

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

FileWriter usage reference

Hack-R
  • 22,422
  • 14
  • 75
  • 131
Amber
  • 507,862
  • 82
  • 626
  • 550
9

From the Javadoc, you can use the constructor to specify whether you want to append or not.

public FileWriter(File file, boolean append) throws IOException

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.

Athafoud
  • 2,898
  • 3
  • 40
  • 58
Peter
  • 6,354
  • 1
  • 31
  • 29
6

You can open the FileWriter in append mode by passing true as the second parameter:

fout = new FileWriter("Distribution_" + ... + ".txt", true);
Matthew Crumley
  • 101,441
  • 24
  • 103
  • 129
3

You may pass true as second parameter to the constructor of FileWriter to instruct the writer to append the data instead of rewriting the file.

For example,

fout = new FileWriter( "Distribution_" + Double.toString(lowerBound) + "" + Double.toString(_highBound) + ".txt",true);

Hope this would solve your problem.

jatanp
  • 3,982
  • 4
  • 40
  • 46