Java I/O: How to append to an already existing text file

空扰寡人 提交于 2019-11-28 08:57:25

问题


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.


回答1:


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




回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/2738448/java-i-o-how-to-append-to-an-already-existing-text-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!