0

I am trying to save the content of the java console into a text file but each time I close the program the text file goes blank and rewrites to it. i.e. if I write to a file today, close the program and come back and run it again tomorrow, it has remembered the information written to it.

jps
  • 20,041
  • 15
  • 75
  • 79
  • 1
    can you paste a small example that reproduces the issue? – Amir Afghani Mar 27 '13 at 23:28
  • Check out [Log4J](http://logging.apache.org/log4j/1.2/). – jahroy Mar 27 '13 at 23:29
  • yes, I am using Scanner class to read the user inputs and using PrintWriter to write them into a file, i am trying to write the data so it remains within the text file and not wiped after each time i close the program. – user2215240 Mar 27 '13 at 23:32
  • No no - paste your code into the question. A description of the code is not going to help us root cause. – Amir Afghani Mar 27 '13 at 23:34
  • @jahroy Using Log4J is pretty much overkill if you aren't doing anything (similar to) logging. Writing simply to a textfile is no excuse, IMHO, to "just use Log4j because it knows how to append". Native streams support appending just as well. – RobIII Mar 27 '13 at 23:38
  • @RobIII - That's true... But it does sound like the OP is after functionality similar to logging: He wants his program to continually append to the same file each time it runs. – jahroy Mar 27 '13 at 23:50
  • @jahroy So you're saying "*continually appending to the same file*" == logging?!? Logging usually implies some sort of format like ` ` (e.g. `2013-03-18T06:46:21 WARNING Foo bar baz`). What if he wants to append customers to a file? What if the application "continually" adds customers to a file because it is 'converting' format A to B and that's all the application does? I think it's not safe to assume that 'continually appending to a file' automatically equals 'logging'; not even by a long shot. – RobIII Mar 28 '13 at 08:48
  • @RobIII - Um... sorry. Nevermind. I made a simple statement saying it was _similar_. Didn't mean to incite a debate (yikes). You are right and my original suggestion was misguided (although all I did was say "_check it out_"). – jahroy Mar 28 '13 at 17:23

1 Answers1

3

You want to open the OutputStream in append mode. Demo code:

PrintWriter out = new PrintWriter(
                     new FileOutputStream(new File(filename), true)); 

What you experience is the normal behavior when you write a stream to a file, and this is not specific to the Java API.

Raffaele
  • 20,627
  • 6
  • 47
  • 86
  • 2
    +1; I would have added a [reference to the documentation]() pointing out the second constructor having a second boolean argument named "append" though for completeness. – RobIII Mar 27 '13 at 23:40
  • Thanks :) Already did that, but hey! cache invalidation on the SO's servers is one of the two hardest things in CS :P – Raffaele Mar 27 '13 at 23:42
  • LOL @ cache invalidation! :D – RobIII Mar 27 '13 at 23:46