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

时间:2010-05-03 04:52:03

标签: java text outputstream writer

我不是java程序员,我是VB程序员。我这样做是作为作业的一部分,但是,我并不是要求与作业相关的帮助。我想弄清楚如何让OutputStreamWriter在这个实例中正常工作。我只想捕获我正在生成的值并将它们放入文本文档中。生成文件,但只存在一个条目,而不是我期望的40个条目。我可以用VB实现这一点,但java现在感觉很奇怪。感谢您的帮助。

谢谢,

史蒂夫

以下是代码:

  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;
  }

1 个答案:

答案 0 :(得分:4)

您正在循环中关闭文件。下一次循环时,你将尝试写入已关闭的文件,这会抛出一个异常...但是你抓住IOException的地方你有一个空块,这将有效地忽略异常。

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

try {
  ...
}
catch ( IOExcetpion e) {
  // Log any errors
}
finally {
  out.close();
}