views:

137

answers:

3

Hi I am having no problem writing to or appending to a file, the only problem is that as soon as I quit the program and then run it again, it creates a new file overwriting my original file. This is a problem, as I am using the text file to keep a running tally.

Is there a way to get an already created text file as an object and then append to it?

Thanks in advance.

+3  A: 

There is a constructor for FileWriter which allows you to set appending with a boolean. javadoc

Poindexter
With apologies, I updated your link so it worked correctly (SO breaks on the space) and also so it links to the current 1.6 docs rather than 1.4.2 (and by name rather than IP). +1, btw
T.J. Crowder
@T.J. thanks, I saw that it was broke and was trying to fix it at the same time.
Poindexter
@Poindexter: No worries. I link to JDK docs a lot so I know the pitfall (replace the space with `%20`).
T.J. Crowder
Thank you, I was unaware of the second parameter - kinda new to this language :)
Joe
+1  A: 

Take a look at java.io.FileWriter. Setting append to true should do the trick.

Robert Petermeier
+5  A: 

Usually, better than FileWriter (already suggested) is to use FileOutputStream, which also (like FileWriter ) has an append parameter in one of its constructors, and which (unlike FileWriter), does not silently assume the default charset encoding (slightly bad practice IMO).

From the FileWriter doc:

Convenience class for writing character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable. To specify these values yourself, construct an OutputStreamWriter on a FileOutputStream.

leonbloy
+1: The lack of an alternative constructor for FileWriter that allows specifying the encoding makes the class nearly useless.
Michael Borgwardt