Ryan Ryan - 28 days ago 19
Java Question

BufferedWriter: Write to file before it is closed

So in my program I have a

BufferedWriter
that is used to create log files of what the program is doing.

private BufferedWriter logWriter;
logWriter = new BufferedWriter(new FileWriter(logFile));


In several classes at several different times I call the below method to continue adding to the log file:

public void log(String logTXT)
{
try
{
logWriter.write(logTXT + "\n");
} catch(Exception e)
{
e.printStackTrace();
}
}


This all works fine, but the one thing that it does, is it doesn't actually write to the file until I call
logWriter.close();
.

What I'd like to see is the String being added to the file immediately after it called the method. Is there anyway that I can go around this, or am I just going to have to live with this, considering it isn't that big of a problem.

Answer

Example of how to append to the end of a file.

    FileWriter fw = new FileWriter("outfilename", true);
    BufferedWriter bw = new BufferedWriter(fw);
    PrintWriter out = new PrintWriter(bw);
    out.println("the text");
    out.println("more text");

The above will peform a flush() for you automatically, you can either flush() yourself or do the above.

The alternative to both would require multiple open and close operations. If this worked for you, please select it as the answer and upvote :)

Comments