0

My question is related to this one. However, I am looking for a way to append the text file over several runs. is there a way to write console output to a text file without erasing the old runs information? I am working on 30+ classes and it would be tedious to change System.out.println statements so I prefer sticking with the System.setOut solution.

I have the following code based on @Mac answer

   PrintStream out = new PrintStream(new FileOutputStream("aa.txt"),true);
   System.setOut(out);

but the file aa.txtdoes not append the results, am I missing something here?

Community
  • 1
  • 1
seteropere
  • 479
  • 1
  • 4
  • 17

3 Answers3

5

When you create a FileWriter or FileOutputStream for your file, pass true as a second argument to the constructor of the FileWriter or FileOutputStream.

FileWriter(File file, boolean append) 
Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110
3

FileWriter and FileOutputStream provide a constructor with an append flag. Just modify the referenced code accordingly

Michael Butscher
  • 10,028
  • 4
  • 24
  • 25
3

You should use:

PrintStream out = new PrintStream(new FileOutputStream("output.txt"),true);
System.setOut(out);
Mac
  • 1,711
  • 3
  • 12
  • 26