我有一个文件(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();
Run Code Online (Sandbox Code Playgroud)
这工作正常,但似乎效率低下,因为我打开文件2次只是为了删除当前内容.
当您打开文件以使用新文本编写文件时,它将覆盖文件中的任何内容.
这样做的好方法是
// empty the current content
fileOut = new FileWriter("file.txt");
fileOut.write("");
fileOut.append("all your text");
fileOut.close();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19208 次 |
| 最近记录: |