0

I am trying to write the console output to the text file (Data.txt) so here is my code:

PrintStream out = new PrintStream(new File("/home/cse/Desktop/Data.txt"));  
System.setOut(out);
out.print("");

When I run the program again after I have once run it, the output replaces the old data that was present in the Data.txt file. But I want it to continue adding the data from where it had stopped earlier. How can I do this?

sphinks
  • 3,048
  • 8
  • 39
  • 55
  • 1
    You first point of call should **always** be the JavaDoc. Just looking at [the list of `PrintStream` constructors](http://docs.oracle.com/javase/8/docs/api/java/io/PrintStream.html#constructor.summary) tells you how to solve this problem. Also please *search* before posting. – T.J. Crowder Dec 11 '15 at 08:53
  • Credit to [sphinks](http://stackoverflow.com/users/1345788/sphinks), who found the original above. – T.J. Crowder Dec 11 '15 at 08:57
  • Take a look on already asked questions: - [Append to text file using PrintStream](http://stackoverflow.com/questions/9805021/append-to-text-file-using-printstream) - [File Write - PrintStream append](http://stackoverflow.com/questions/8043356/file-write-printstream-append) – sphinks Dec 11 '15 at 08:55

2 Answers2

2

You need to pass a FileOutputStream created with the constructor that accepts an append flag:

PrintStream out = new PrintStream(new FileOutputStream("/home/cse/Desktop/Data.txt", true)); 

The true states the new content will be appended to an existing file.

Dennis Kriechel
  • 3,719
  • 14
  • 40
  • 62
-2

Using out.append() should do the job for you.

PrintStream out = new PrintStream(new File("/home/cse/Desktop/Data.txt"));  
System.setOut(out);
out.append("");