views:

218

answers:

2

Okay... so I have a fairly interesting error... I declare a FileWriter called file, and I have it go through the following for loops:

for (int i = 0; i < a.radtot; i++) {
    file.write("" + i * a.rstep);

    for (int n = 0; n < a.timetot; n++) {
        file.write("\t " + T[n][i]);
        System.out.println(T[n][i] + " " + n + " " + i);
    }

    file.write("\n");
}

At the end of it, the System.out.println command prints what I expect it to, but the file cuts off midway... As in, instead of printing out everything System.out does... it stops in the middle. Does anyone happen to know why it would do that? Am I doing something wrong?

+5  A: 

You need to call close() on the FileWriter when you're done with it. This forces all output to be actually written to disk (it could be left in a buffer otherwise).

for (int i = 0; i < a.radtot; i++) {
    file.write("" + i * a.rstep);

    for (int n = 0; n < a.timetot; n++) {
        file.write("\t " + T[n][i]);
        System.out.println(T[n][i] + " " + n + " " + i);
    }

    file.write("\n");
}
file.close(); // <-- Add this

(I'm assuming you've omitted exception handling for brevity, so I have done the same. The close() would ordinarily be in a finally block to ensure that it will always run.)

Michael Myers
Thank you, this worked.
wolfPack88
Technically speaking flush() was what was missing, but close() is a good idea in any case.
Kathy Van Stone
Yes, I think the Javadocs make that clear (and I didn't want to clutter the answer up).
Michael Myers
+3  A: 

Try adding:

file.close();

The close() method description says:

Closes the stream, flushing it first.

Jared Oberhaus
Thank you, this worked.
wolfPack88