首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >尝试编写使用OutputStream写入文本文件的循环

尝试编写使用OutputStream写入文本文件的循环
EN

Stack Overflow用户
提问于 2010-05-03 12:52:03
回答 1查看 7.3K关注 0票数 1

我不是java程序员,我是VB程序员。我这样做是作为一项任务的一部分,但是,我并不是在请求与任务相关的帮助。我想弄清楚如何在这种情况下让OutputStreamWriter正常工作。我只想捕获我正在生成的值,并将它们放入文本文档中。文件已生成,但只存在一个条目,而不是我期望的40个条目。我可以用VB在瞬间做到这一点,但java现在对我来说非常陌生。非常感谢您的帮助。

谢谢,

史蒂夫

代码如下:

代码语言:javascript
复制
  public static void main(String[] args) {
    long start, end;
    double result,difference;

    try {
      //OutputStream code assistance from 
      // http://tutorials.jenkov.com/java-io/outputstreamwriter.html
      OutputStream outputStream = new FileOutputStream("c:\\Temp\\output1.txt");
      Writer out = new OutputStreamWriter(outputStream);

      for(int n=1; n<=20; n++) {
        //Calculate the Time for n^2.
        start = System.nanoTime();

        //Add code to call method to calculate n^2
        result =  mN2(n);
        end = System.nanoTime();
        difference = (end - start);

        //Output results to a file
        out.write("N^2 End time: " + end + " Difference: " + 
            difference + "\n");
        out.close();
      }
    } catch (IOException e){
    }

    try {
      OutputStream outputStream = new FileOutputStream("c:\\Temp\\output1.txt");
      Writer out = new OutputStreamWriter(outputStream);

      for(int n=1; n<=20; n++){
        //Calculate the Time for 2^n.
        start = System.nanoTime();
        //Add code to call method to calculate 2^n
        result =  m2N(n);
        end = System.nanoTime();
        difference = (end - start);
        //Output results to a file
        out.write("N^2 End time: " + end + " Difference: " + difference + "\n");
        out.close();
      }
    } catch (IOException e){
    }
  }

  //Calculate N^2
  public static double mN2(double n) {
    n = n*n;
    return n;
  }

  //Calculate 2N
  public static double m2N(double n) {
    n = 2*n;
    return n;
  }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2010-05-03 13:01:13

你在循环中关闭你的文件。在下一次循环中,您将尝试写入关闭的文件,这将抛出一个捕获IOException的exception...but,其中有一个空块,它将有效地忽略该异常。

尝试将out.close()调用移动到finally块中,如下所示:

代码语言:javascript
复制
try {
  ...
}
catch ( IOException e) {
  // Log any errors
}
finally {
  out.close();
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2756170

复制
相关文章

相似问题

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