• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Help writing data to a file

 
charlie mills
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I want to add data to an already existing file, and I just want to add the data to the end of the list in a text file.
I've written this but it creates a new file each time and wipes out all the old data.



How do I add the data to an already existing file?
 
Campbell Ritchie
Sheriff
Posts: 48381
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The only way I have ever found to add data to a text file is the old-fashioned way with a BufferedWriter and a FileWriter. Look closely in the FileWriter constructors where you find hints about appending.
Like most things there is something about it in the Java Tutorials.
Also see if you can find an example of closing the writers in a finally block. I am not sure I would use a PrintStream; look closely at its API documentation and it tells you why, but if I did use a PrintStream it would read something like this:The finally makes sure that the file is closed even if an Exception occurs in the while loop. It has to be surrounded by a try-catch because it may itself throw an Exception. The PrintStream is declared outside the try-catch otherwise it would go out of scope. If there is an Exception, the PrintStream reference may be null at the beginning of the finally, hence the if (out != null) test. A flush() call is not usually necessary; see what the API says about close().

And good luck with it
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic