使用RandomAccessFile清除Java中的文件内容

我试图清除我在java中创建的文件的内容。 该文件由PrintWriter调用创建。 我在这里读到可以使用RandomAccessFile这样做,并在其他地方读取,这实际上比调用新的PrintWriter并立即关闭它以使用空白覆盖文件更好。

但是,使用RandomAccessFile不起作用,我不明白为什么。 这是我的代码的基本大纲。

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

运行相当于上面的代码给我的临时文件的内容:
(让我们假设程序在clearCondition满足之前循环两次)

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

注意:写入程序需要能够在清除文件后再次将“示例文本”写入文件。 clearCondition并不意味着while循环被破坏。

您希望刷新PrintWriter以确保在将RandomAccessFile的长度设置为0之前首先写出其缓冲区中的更改,或者关闭它并重新打开新的PrintWriter以写入最后一行(Text to be书面…)。 前者最好:

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

如果同时打开文件两次,你会很幸运。 它没有指定由Java工作。

你应该做的是关闭PrintWriter并打开一个没有’append’参数的新的,或者’append’设置为’false’。