Clear contents of a file in Java using RandomAccessFile

≡放荡痞女 提交于 2019-12-02 12:27:39

You want to either flush the PrintWriter to make sure the changes in its buffer are written out first, before you set the RandomAccessFile's length to 0, or close it and re-open a new PrintWriter to write the last line (Text to be written...). Preferably the former:

if (clearCondition) {
writer.flush();
new RandomAccessFile("temp","rw").setLength(0);

You'll be lucky if opening the file twice at the same time works. It isn't specified to work by Java.

What you should do is close the PrintWriter and open a new one without the 'append' parameter, or with 'append' set to 'false'.

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