我正在做一个学校的作业,并且正在尝试一些额外的学分以外的东西。该程序是为了演示给定整数数组大小的线性和二进制搜索之间的效率差异。我设置了一个循环,创建一个intsize数组,搜索一个随机数,然后创建一个intsize*2的新数组。
然后将结果写入文本文件。输出写得很好,但是在多次编译和运行程序之后,输出文件就有那么多的数据部分。
下面是嵌套在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;
}
}有没有办法在每次程序运行时擦除输出文件中的文本?
我这样做的原因是,教授要求打印出带有图表数据的结果。我已经完成了绘图要求,它工作得很好。我只想让文件打印输出与图形打印输出相匹配。
发布于 2010-01-25 01:21:23
如前所述,FileWriter构造函数允许您指定清除现有文本并从文件开头开始。关于代码的其他一些备注:
如下所示:
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
发布于 2010-01-25 00:54:12
FileWriter构造函数的第二个参数是"append“。也就是说,因为您已将其设置为true,所以它会将新输出附加到文件的末尾。如果你传入的是false,它将擦除已经存在的数据并写入新的数据。
发布于 2010-01-25 00:54:21
阅读FileWriter的文档。You do not to append. (你不想追加。
https://stackoverflow.com/questions/2127862
复制相似问题