2010-05-03 45 views
1

我不是一个java程序员,我是一名VB程序员。我将此作为一项任务的一部分,但是,我并没有要求有关任务的帮助。在这种情况下,我想弄清楚如何让OutputStreamWriter正常工作。我只想捕获我生成的值并将它们放入文本文档中。该文件生成,但只有一个条目存在,而不是我期待的40。我可以用VB来做到这一点,但是现在我觉得Java很奇怪。感谢您的帮助。试图编写一个使用OutputStream写入文本文件的循环

感谢,

史蒂夫

下面的代码:

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

回答

4

你在循环中关闭您的文件。下次在循环中,你将尝试写入封闭的文件,这将抛出一个异常......但是你在哪里捕获到了一个空块,它将有效地忽略异常。

尝试out.close()呼叫移动到finally块,像这样:

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