RandomAccessFile setLength(0)将一个空字符串添加到文件中

时间:2014-02-01 01:53:32

标签: java null character clear randomaccessfile

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

但是,使用RandomAccessFile清除文件似乎是在文件中添加了一串空字符(或者可能是PrintWriter?)只有在添加更多文本时才会出现。

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

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

if (clearCondition) {
writer.flush();
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();

运行上述代码的等价物,为我的临时文件提供内容:

^@^@^@^@^@^@^@^@^@^@^@^@^@Text to be written onto the first line of temp file

空字符数等于已删除的字符数(包括换行符)。如果没有新文本添加到文件中,则它完全空白。

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

编辑:我不知道导致这些空字符的原因。我意识到我是愚蠢的,没有必要有一个临时文件,只是一个临时字符串,其中包含以后写入文件的所有数据。使用=“”可以非常轻松地重置字符串;感谢所有建议

1 个答案:

答案 0 :(得分:1)

在文件上打开PrintWriter并同时使用RandomAccessFile似乎不太好。

如果您关闭作家并在文件上打开一个新作者(而不是使用RandomAccessFile),我认为它将满足您的需求。