wolfPack88
wolfPack88

Reputation: 4203

Java FileWriter help

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?

Upvotes: 0

Views: 1698

Answers (2)

Jared Oberhaus
Jared Oberhaus

Reputation: 14678

Try adding:

file.close();

The close() method description says:

Closes the stream, flushing it first.

Upvotes: 3

Michael Myers
Michael Myers

Reputation: 192055

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.)

Upvotes: 5

Related Questions