When should I close() a BufferedWriter?

intagli picture intagli · Jul 27, 2011 · Viewed 10.4k times · Source

I'm appending a line to a textfile each time a button is pressed. Currently I'm doing this each time the button is pressed:

...
try {
        BufferedWriter bw = new BufferedWriter(new FileWriter(f, true));
        if (fileIsNew == true)
            bw.write(firstLine);
        bw.write(string);
        bw.close();
        Log.v("file", "written to file:" + f.getAbsolutePath());
    } catch (IOException e) {
        Log.v("IOException", e.toString());
    }
...

I don't think it's really a good idea to close the bufferedwriter after each line as the purpose of a bufferedWriter is to buffer the output, right?

So when should I call bw.close() ? And should I create the new BufferedWriter in some kind of init()? I think it's inefficient to create a new BufferedWriter each time the button is pressed.

Answer

MByD picture MByD · Jul 27, 2011

You can declare it as a member field, create it upon first press on the button, by setting a flag, and keep it open.

On each press, call write() and then flush() (to avoid content loss).

BufferedWriter bw;
boolean isOpen = false;
// ..
try {
    if (!isOpen) {
        bw = new BufferedWriter(new FileWriter(logFile, true));
        bw.write(firstLine);
        isOpen = true;
    }
    bw.write(string);
    bw.flush();
    Log.v("file", "written to file:" + logFile.getAbsolutePath());
} catch (IOException e) {
    Log.v("IOException", e.toString());
}