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

编程入门 行业动态 更新时间:2024-10-24 02:26:50
本文介绍了使用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中的文件内容

本文发布于:2023-11-03 16:25:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1555574.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   内容   RandomAccessFile   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!