views:

88

answers:

1

I'm not a java programmer, I'm a VB programmer. I am doing this as part of an assignment, however, I'm not asking for help on something assignment related. I'd like to figure out how to get the OutputStreamWriter to work properly in this instance. I just want to capture the values I'm generating and place them into a text document. The file is generated, but only one entry exists, not the 40 I'm expecting. I could do this in a heartbeat with VB, but java feels very strange to me right now. Your help is appreciated.

Thanks,

Steve

Here's the code:

  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;
  }
+2  A: 

You're closing your file within the loop. The next time around the loop you will attempt to write to the closed file, which will throw an exception...but where you catch IOException you have an empty block, which will effectively ignore the exception.

Trying moving the out.close() call into a finally block, like this:

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