簡體   English   中英

嘗試編寫一個使用OutputStream寫入文本文件的循環

[英]Trying to write a loop that uses an OutputStream to write to a text file

我不是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;
  }

你正在循環中關閉你的文件。 下一次循環時,您將嘗試寫入已關閉的文件,這將引發異常...但是在您捕獲IOException您有一個空塊,這將有效地忽略該異常。

嘗試將out.close()調用移動到finally塊中,如下所示:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM