Updating a text file using BufferedWriter

I write to a text file using BufferedWriter, but BufferedWriter does not write the file until the program that I run is finished, and I am not sure how to update it, since BufferedWriter supposedly writes. Here are some of my codes 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 am doing a BufferedWriter reset, but I still don't have the file as soon as it is written, but instead, when the program ends. Any suggestions?

+3
source share
3 answers

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

, flush() in finally , close() .

+3

:

, , PrintWriter, - flush .
: 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]);
}

:
PrintWriter(Writer out, boolean autoFlush), , Javadoc, :

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

, , .

0

, , , :

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
}

flush() , finally {} , try {} catch {}.

0

Source: https://habr.com/ru/post/1733277/


All Articles