0

Alright so this is a general question which probably has an obvious answer. How would I go about having a program that outputs to a data file, and everytime it is rerun I would skip to the next line.

So for example..

If I wanted to write the word "hi" to a data file, and when it rerun there would then be two "hi"'s without the previous one being deleted.

Sorry this is a proof of concept type thing so I dont have any actual code to post with this question.

  • 3
    The PrintWriter class, among others, has an append() method I would look into. This link has a great example http://stackoverflow.com/questions/1625234/how-to-append-text-to-an-existing-file-in-java – Kon Jul 09 '13 at 19:02
  • 1
    @Kon Looked at that link and applied and it works great! Thank you :) – user2445983 Jul 09 '13 at 19:07
  • I didn't realize you could put true after the file you outputting to, and that it wouldn't delete the previous entry. Really appreciate the quick response – user2445983 Jul 09 '13 at 19:09
  • 1
    By the way, this sort of thing is called "appending" to the file, in case you need to ask about it later when using another framework or programming language. "Writing" will overwrite the previous contents of the file; "appending" will not. – ameed Jul 09 '13 at 19:12

2 Answers2

2

When you open up a FileOutputStream to the file to write to, use the constructor that takes the File (or String file name) and a boolean append option and set that append option to true. From there, you can wrap whatever stream decorator (PrintWriter for example) around that input stream and you should be good to go.

PrintWriter out = new PrintWriter(new FileOutputStream(fileName, true));
cmbaxter
  • 35,283
  • 4
  • 86
  • 95
  • 1
    Yes. I didn't realise you could do that until the first kon provided a link that showed this concept. And I'm good to go now thank you! – user2445983 Jul 09 '13 at 19:10
1

You can do something like this:

try
{
    String filename= "file.txt";
    FileWriter fw = new FileWriter(filename,true); 
    fw.write("this is a new line\n");
    fw.close();
}
catch(IOException ioe)
{
    // Error!
    System.err.println("IOException: " + ioe.getMessage());
}
jh314
  • 27,144
  • 16
  • 62
  • 82