java 如何擦除文件中的现有文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2127862/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to erase existing text in a file
提问by Jason
I'm working on an assignment for school, and am trying something beyond for extra credit. The program is to demonstrate the efficiency differences between a linear & binary search for a given array size of integers. I have a loop set up that creates an int[size] array, searches for a random number, then creates a new array of int[size*2].
我正在为学校完成一项作业,并且正在尝试其他一些事情以获得额外的学分。该程序将演示对给定的整数数组大小进行线性搜索和二分搜索之间的效率差异。我有一个循环设置,它创建一个 int[size] 数组,搜索一个随机数,然后创建一个新的 int[size*2] 数组。
The results are then written to a text file. The output writes fine, but after compiling & running the program several times, the output file has that many sections of data.
然后将结果写入文本文件。输出写得很好,但是在多次编译和运行程序之后,输出文件中有那么多的数据部分。
This is my code that is nested inside a try/catch block:
这是我嵌套在 try/catch 块中的代码:
File output= new File("c:\BigOhResults.txt");
int counter=2;
if (output.canWrite() && output.exists()) {
BufferedWriter out= new BufferedWriter(new FileWriter(output, true));
out.write(type+" \n\n"); //writes the search type
out.write(type+"Search Results\n\n");
while (counter <= data.size()) {
out.write(data.get(counter-1)+" millisecond runtime " +
"for a "+ data.get(counter-2)+" random number " +"sample size\n");
counter=counter+2;
}
}
Is there any way I can erase the text within that output file upon each time the program is run?
有什么办法可以在每次运行程序时擦除该输出文件中的文本?
the reason I'm doing this is the professor requires the result printout with the data graphed. I have already completed the graphing requirement, and it works fine. I just want to have the file printout match the graph printout.
我这样做的原因是教授要求将结果打印出来并绘制数据。我已经完成了绘图要求,它工作正常。我只想让文件打印输出与图形打印输出匹配。
采纳答案by mangoDrunk
As already mentioned, the [FileWriter][1] constructor allows you to specify to clear the existing text and start at the beginning of the file. Some other remarks about the code:
如前所述,[FileWriter][1] 构造函数允许您指定清除现有文本并从文件开头开始。关于代码的其他一些说明:
- The check on output.exists() is redundant after a call to output.canWrite() and isn't needed. output.canWrite() will check if the file exists and that you can write to it.
- Don't forget to close the BufferedWriter object.
- 在调用 output.canWrite() 之后,对 output.exists() 的检查是多余的,不需要。output.canWrite() 将检查文件是否存在以及您是否可以写入。
- 不要忘记关闭 BufferedWriter 对象。
Like so:
像这样:
if (output.canWrite()) {
BufferedWriter out = null;
try {
out = new BufferedWriter(new FileWriter(output, false));
out.write(type+" \n\n"); //writes the search type
out.write(type+"Search Results\n\n");
while (counter <= data.size()) {
out.write(data.get(counter-1)+" millisecond runtime " +
"for a "+ data.get(counter-2)+" random number " +"sample size\n");
counter=counter+2;
}
} catch (IOException e) {
// Do what you want here, print a message or something
} finally {
if(out != null) {
try {
out.close();
} catch (IOException e) {
// Again, do what you want here
}
}
}
}
[1]: http://java.sun.com/j2se/1.4.2/docs/api/java/io/FileWriter.html#FileWriter(java.io.File, boolean)
[1]:http: //java.sun.com/j2se/1.4.2/docs/api/java/io/FileWriter.html#FileWriter(java.io.File, boolean)
回答by Paul Tomblin
The second argument to the FileWriter constructor, which you're passing in "true", is "append". I.e. because you've set it to true, it will append your new output to the end of the file. If you pass in false instead, it will wipe the data that's there already and write it new.
您传入“true”的 FileWriter 构造函数的第二个参数是“append”。即因为您已将其设置为 true,它会将您的新输出附加到文件的末尾。如果您改为传入 false,它将擦除已经存在的数据并将其写入新的数据。
回答by Charlie Salts
Read the documentation for FileWriter. You do notwant to append.
阅读FileWriter的文档。你不是要追加。
回答by Ramprasad Dutt
Okay so I tried something and it worked. This is when you have a file that is intended to append any new text, but you want to reset/erase the contents of the file at the beginning of program execution. Hope I made sense.
好的,所以我尝试了一些东西并且它起作用了。这是当您有一个旨在附加任何新文本的文件,但您想在程序执行开始时重置/擦除文件的内容时。希望我说的有道理。
PrintWriter pw1 = new PrintWriter(new BufferedWriter(new FileWriter("newfile.txt")));
pw1.close(); // Make sure the first PrintWriter object name is different from the second one.
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("newfile.txt", true))); // PrintWriter in append-mode. When you recreate the text file with the same name, the file contents are erased because the previous object was not in append mode.
pw.close();

