首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何擦除文件中的现有文本

如何擦除文件中的现有文本
EN

Stack Overflow用户
提问于 2010-01-25 00:49:15
回答 4查看 13.5K关注 0票数 7

我正在做一个学校的作业,并且正在尝试一些额外的学分以外的东西。该程序是为了演示给定整数数组大小的线性和二进制搜索之间的效率差异。我设置了一个循环,创建一个intsize数组,搜索一个随机数,然后创建一个intsize*2的新数组。

然后将结果写入文本文件。输出写得很好,但是在多次编译和运行程序之后,输出文件就有那么多的数据部分。

下面是嵌套在try/catch块中的代码:

代码语言:javascript
复制
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;
    }
}

有没有办法在每次程序运行时擦除输出文件中的文本?

我这样做的原因是,教授要求打印出带有图表数据的结果。我已经完成了绘图要求,它工作得很好。我只想让文件打印输出与图形打印输出相匹配。

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2010-01-25 01:21:23

如前所述,FileWriter构造函数允许您指定清除现有文本并从文件开头开始。关于代码的其他一些备注:

  • 在调用output.canWrite()之后,对output.exists()的检查是多余的,并且不需要。output.canWrite()将检查文件是否存在以及是否可以写入。
  • 不要忘记关闭BufferedWriter对象。

如下所示:

代码语言:javascript
复制
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

票数 3
EN

Stack Overflow用户

发布于 2010-01-25 00:54:12

FileWriter构造函数的第二个参数是"append“。也就是说,因为您已将其设置为true,所以它会将新输出附加到文件的末尾。如果你传入的是false,它将擦除已经存在的数据并写入新的数据。

票数 5
EN

Stack Overflow用户

发布于 2010-01-25 00:54:21

阅读FileWriter的文档。You do not to append. (你不想追加。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2127862

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档