Java I/O:如何追加到已存在的文本文件
您好,我在写入或附加文件时没有问题,唯一的问题是,一旦我退出程序然后再次运行它,它会创建一个新文件覆盖我的原始文件。这是一个问题,因为我正在使用文本文件来保持运行计数。
有没有办法将已经创建的文本文件作为对象然后附加到它?
提前致谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
通常,比 FileWriter (已经建议)更好的是使用 FileOutputStream,它也(如
FileWriter
)在其构造函数之一中有一个append
参数,并且它(与FileWriter
不同)不会默默地采用默认的字符集编码(在我看来,这种做法有点不好)。来自 FileWriter 文档:
Usually, better than FileWriter (already suggested) is to use FileOutputStream, which also (like
FileWriter
) has anappend
parameter in one of its constructors, and which (unlikeFileWriter
), does not silently assume the default charset encoding (slightly bad practice IMO).From the FileWriter doc:
FileWriter 有一个构造函数,允许您使用布尔值设置附加。
javadoc
There is a constructor for FileWriter which allows you to set appending with a boolean.
javadoc
看一下 java.io.FileWriter。将
append
设置为 true 应该可以解决问题。Take a look at java.io.FileWriter. Setting
append
to true should do the trick.