java打开文件清空,使用RandomAccessFile清除Java中的文件内容

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.

解决方案

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值