Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/391.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何清空文件内容,然后多次追加文本_Java_File Io - Fatal编程技术网

Java 如何清空文件内容,然后多次追加文本

Java 如何清空文件内容,然后多次追加文本,java,file-io,Java,File Io,我有一个文件(file.txt),我需要清空他的当前内容,然后多次附加一些文本 示例:file.txt当前内容为: aaa bbb ccc 我想删除此内容,然后第一次追加: ddd 第二次: eee 等等 我试过这个: // empty the current content fileOut = new FileWriter("file.txt"); fileOut.write(""); fileOut.close(); // append fileOut = new FileWriter("

我有一个文件(file.txt),我需要清空他的当前内容,然后多次附加一些文本

示例:file.txt当前内容为:

aaa

bbb

ccc

我想删除此内容,然后第一次追加:

ddd

第二次:

eee

等等

我试过这个:

// empty the current content
fileOut = new FileWriter("file.txt");
fileOut.write("");
fileOut.close();

// append
fileOut = new FileWriter("file.txt", true);

// when I want to write something I just do this multiple times:
fileOut.write("text");
fileOut.flush();

这很好,但效率似乎很低,因为我打开文件两次只是为了删除当前内容。

当您打开文件以写入新文本时,它将覆盖文件中已有的内容

这样做的一个好方法是

// empty the current content
fileOut = new FileWriter("file.txt");
fileOut.write("");
fileOut.append("all your text");
fileOut.close();

第一个答案是不正确的。如果使用第二个参数的true标志创建新的filewriter,它将以追加模式打开。这将导致任何写入(字符串)命令将文本“附加”到文件末尾,而不是清除已经存在的任何文本。

我太笨了

我只需要这样做:

// empty the current content
fileOut = new FileWriter("file.txt");

// when I want to write something I just do this multiple times:
fileOut.write("text");
fileOut.flush();

最后关闭流。

我发现这个问题在很多Java版本之前就得到了回答。。。 从Java 1.7开始,使用新的FileWriter+BufferWriter+PrintWriter进行追加(如中所建议),我建议先删除文件,然后追加:

FileWriter fw = new FileWriter(myFilePath); //this erases previous content
fw = new FileWriter(myFilePath, true); //this reopens file for appending 
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
pw.println("text"); 
//some code ...
pw.println("more text"); //appends more text 
pw.flush();
pw.close();

我能想到的最好的办法是:

Files.newBufferedWriter(pathObject , StandardOpenOption.TRUNCATE_EXISTING);

在这两种情况下,如果pathObject中指定的文件是可写的,则该文件将被截断。 不需要调用write()函数。上面的代码足以清空/截断一个文件


希望能有所帮助

事实上,你不需要关闭它然后再打开它。你读了我的评论很好,但是你最好还是编辑上一个问题。答案应该是独立的,没有必要参考“第一个”答案,特别是因为stackoverflow不会以这种方式排列问题。我尝试过这样做,但我没有看到答案上的“添加评论”按钮。有什么我遗漏的吗?你还没有足够的声誉。给stackoverflow一些时间来发布答案Pierpaolo。这是一个“游戏”网站,不要在第一天左右回答你自己的问题。对不起。我必须删除我的答案吗?不,随它去吧,这个问题现在已经可以回答了,给别人留点时间下次再回答。@owlstead:“不要在第一天左右回答你自己的问题”为什么不呢?@BoltClock好吧,当你输入你的答案时,人们正在写答案。他们花时间读了一遍,想了想才发现作者的发帖有点过早。这并不是说这种问题不可能在最初的30分钟内得到正确的回答(在这种情况下,一天可能有点长)
Files.newInputStream(pathObject , StandardOpenOption.TRUNCATE_EXISTING);