Clear contents of a file in Java using RandomAccessFile

倾然丶 夕夏残阳落幕 提交于 2019-12-31 05:29:15

问题


I am trying to clear the contents of a file I made in java. The file is created by a PrintWriter call. I read here that one can use RandomAccessFile to do so, and read somewhere else that this is in fact better to use than calling a new PrintWriter and immediately closing it to overwrite the file with a blank one.

However, using the RandomAccessFile is not working, and I don't understand why. Here is the basic outline of my code.

PrintWriter writer = new PrintWriter("temp","UTF-8");

while (condition) {
writer.println("Example text");

if (clearCondition) {
new RandomAccessFile("temp","rw").setLength(0);
      //  Although the solution in the link above did not include ',"rw"'
      //  My compiler would not accept without a second parameter
writer.println("Text to be written onto the first line of temp file");
}
}
writer.close();

Running the equivalent of the above code is giving my temp file the contents:
(Lets imagine that the program looped twice before clearCondition was met)

Example Text
Example Text
Text to be written onto the first line of temp file



NOTE: writer needs to be able to write "Example Text" to the file again after the file is cleared. The clearCondition does not mean that the while loop gets broken.


回答1:


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);



回答2:


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'.



来源:https://stackoverflow.com/questions/21488985/clear-contents-of-a-file-in-java-using-randomaccessfile

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