使用RandomAccessFile清除Java中的文件内容 [英] Clear contents of a file in Java using RandomAccessFile

查看:2455
本文介绍了使用RandomAccessFile清除Java中的文件内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

但是,使用RandomAccessFile不起作用,我不明白为什么。以下是我的代码的基本概要。

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

运行上述代码的等价物为我的临时文件提供内容:
(让我们假设程序在满足clearCondition之前循环两次)

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




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



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.

推荐答案

你想要刷新 PrintWriter 以确保在将 RandomAccessFile 的长度设置为0之前,先将其缓冲区中的更改写出,或者将其关闭并重新打开一个新的 PrintWriter 来写最后一行(要写的文本......)。优选前者:

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

这篇关于使用RandomAccessFile清除Java中的文件内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆