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

问题描述 投票:0回答:2

我正试图清除我在java中制作的一个文件的内容,这个文件是由PrintWriter调用创建的。 该文件是由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

注意:writer需要在文件被清空后,能够再次向文件写入 "例文"。 clearCondition并不意味着while循环被破坏。

java file randomaccessfile
2个回答
4
投票

你想冲掉 PrintWriter 以确保缓冲区中的变化首先被写出来,然后再设置 RandomAccessFile的长度为0,或者关闭它并重新打开一个新的 PrintWriter 写下最后一行(要写的文字...)。最好是前者。

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

0
投票

如果在同一时间打开文件两次,你会很幸运。Java并没有指定它的工作方式。

你应该做的是关闭PrintWriter,然后打开一个新的,不使用'append'参数,或者将'append'设置为'false'。

© www.soinside.com 2019 - 2024. All rights reserved.