Java – how to use flush() in printwriter
I have some code like this:
PrintWriter pw = new PrintWriter(new BufferedReader(....)); for(int i=0; i<10; i++) { pw.println("a"); pw.flush();// flush each time when println()? } pw.close();
Must flush() in each 'for' statement? I heard that flush () is called automatically when close () is called If I write this Code:
PrintWriter pw = new PrintWriter(new BufferedReader(....),true);
I can't write PW Flush()? thank you.
Solution
In your example, flush () may not be required
What it does is ensure that anything written to the author before calling flush () is written to the underlying stream instead of sitting in some internal buffer
This method is useful in several cases:
>If another process (or thread) needs to check the file when writing to it, and it is important for other processes to see all recent writes. > If the writing process may crash, it is important not to lose writing to the file. > If you are writing to the console and need to make sure that every message will be displayed after writing