File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Help writing data to a file Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Help writing data to a file" Watch "Help writing data to a file" New topic

Help writing data to a file

charlie mills
Ranch Hand

Joined: Nov 01, 2008
Posts: 49
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

Joined: Oct 13, 2005
Posts: 46320
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
I agree. Here's the link:
subject: Help writing data to a file
jQuery in Action, 3rd edition