-1

I'm using a BufferedWriter to write some data to a textfile. It's faster than using ODBC to write to Access. Code looks something like this:

BufferedWriter bw = new BufferedWriter(new FileWriter(new File(filePath), true));

True is to make the BufferedWriter append, not overwrite.

bw.append(          
    country + "\t" +
    scenario + "\t" +
    tempStage + "\t" +
    year + "\t" +
    tempState
);

It's worked for me in previous projects. New problem: it just craps out in the middle of the line. This is a good line:

SultanateOfBrunei   BeeBeeScenario  Other   2019

The last line typically looks like this:

SultanateOfBrunei   BeeBeeScenario  Other   2019 Nondyna

or Sulta

or even Su

I put in error handling code to ignore weird incomplete lines like that.

This means not all the data is being written. I can give up one datum, no problem... But it appears to be cutting out more. The simulation runs 1990 to the end of 2020 and it typically craps out somewhere in 2019. Increasing the VM helps a little-- it gets further. But I only have a certain amount of memory!

Any insights?

Thanks!!

hmjd
  • 120,187
  • 20
  • 207
  • 252
user1507455
  • 1,083
  • 2
  • 10
  • 10

4 Answers4

5

Your application is probably not closing the BufferedWriter, and as a result the last part of the output is not being written out to the file.

The structure of your program should be something like this:

BufferedWriter bw = new BufferedWriter(new FileWriter(new File(filePath), true));
try {
    // generate output
} finally {
    bw.close();
}

Note that this doesn't attempt to handle the I/O exceptions that might arise while opening, writing to or closing the writer. Whether you should do that, and what you should do with any exceptions that you catch depends on the circumstances.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
1

Probably you are not flushing (bw.flush()) the stream before closing it. That should be done to all streams, but it is more critical to buffered ones.

SJuan76
  • 24,532
  • 6
  • 47
  • 87
1

You just need to close the BufferedWriter. If you dont, the last filled buffer might not get written.

havexz
  • 9,550
  • 2
  • 33
  • 29
1

Once you're done writing, you should essentially call close() on your BufferedWriter object. This would ensure that the your stream is flushed and consequently closed.

Sujay
  • 6,753
  • 2
  • 30
  • 49