Update text file with BufferedWriter

Brandon picture Brandon · Feb 17, 2010 · Viewed 9k times · Source

I am writing to a text file using a BufferedWriter but the BufferedWriter does not write to the file until the program I'm running is finished and I'm not sure how to update it as the BufferedWriter is supposedly writing. Here is some of my code that I have:

FileWriter fw = null;
try {
    fw = new FileWriter("C:/.../" + target + ".pscr",true);
    writer = new BufferedWriter(fw);
    writer.write(target);
    writer.newLine();
    writer.write(Integer.toString(listOfFiles.length));
    writer.newLine();
    for(int i=0; i < listOfFiles.length; i++){
        writer.write(probeArray[i] + "\t" + probeScoreArray[i]);
        writer.newLine();                               
    }                           
}
catch (IOException e1) {e1.printStackTrace();}
catch (RuntimeException r1) {r1.printStackTrace();}
finally {
    try {
        if(writer != null){
            writer.flush();
            writer.close();
        }
    }
    catch (IOException e2) {e2.printStackTrace();}
}

I do flush the BufferedWriter but still have no file as soon as it writes, but instead when the program finishes. Any suggestions?

Answer

BalusC picture BalusC · Feb 17, 2010

You need to move the flush() call into the try block. For example after every newLine() call.

That said, the flush() in finally is superfluous as close() already implicitly calls it.