开发者

Update text file with BufferedWriter

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?


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.


Just to be completely clear, this is where you need to add the flush, if you want to flush each line as it's written:

for(int i=0; i < listOfFiles.length; i++){
    writer.write(probeArray[i] + "\t" + probeScoreArray[i]);
    writer.newLine();
    writer.flush(); // Make sure the flush() is inside the for loop
}

In your code, the flush() isn't happening until the end of the program, because the finally{} block doesn't execute until after the try{} or catch{} block has finished executing.


Skip the buffering completely:

You're only every printing whole lines as it is, so the benefits it offers over a PrintWriter is lost in the the example above, due to the flush calls after every line write.
As described here: http://java.sun.com/javase/6/docs/api/java/io/BufferedWriter.html

PrintWriter pw = null;
try {
    pw = new PrintWriter(new FileWriter("C:/.../" + target + ".pscr", true), true);
    pw.println(target);
    pw.println(Integer.toString(listOfFiles.length));
    for(int i=0; i < listOfFiles.length; i++)
        pw.println(probeArray[i] + "\t" + probeScoreArray[i]);
}

Last update:
Called the PrintWriter(Writer out, boolean autoFlush) constructor, which according to the Javadoc, has the following behavior:

autoFlush - if true, the println, printf, or format methods will flush the output buffer

If this doesn't work I don't know what will..

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜