How to write to a file and save it dynamically in java

java, java-io

Solution

You don't need to call `close()` - just call `flush()`.

Flushes this output stream and forces any buffered output bytes to be written out.

Problem

I have a requirenment to write to a file rather than in System.out.println and save it at same time so that user can see the progress anytime by opening the file. Right now I am using following code ``` FileWriter fstream = null; File file1 = new File(logFile); fstream = new FileWriter(file1); out = new BufferedWriter(fstream); out.write(msg); out.write("\n"); ``` but it does not save the contents to the file unless I say Out.close(); FYI - 1. This is a Java EE application code. 2. I donot want to user Log4jLogger Is there any simpler way to do this? Any pointers?

Original source