How to use flush() for PrintWriter
Asked Answered
M

3

15

I have some codes 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();

Is the flush() in each 'for' statement necessarily? I heard that flush() would auto invoke when invoke close() . If I write code like this:

PrintWriter pw = new PrintWriter(new BufferedReader(....), true);

and I wouldn't write pw.flush() anymore? Thanks.

Marcelenemarcelia answered 29/3, 2012 at 14:21 Comment(1)
There is no need to flush inside loops like this You are losing the benefit of any buffering.Amieeamiel
B
23

flush() is probably not required in your example.

What it does is ensure that anything written to the writer prior to the call to flush() is written to the underlying stream, rather than sit in some internal buffer.

The method comes in handy in several types of circumstances:

  1. If another process (or thread) needs to examine the file while it's being written to, and it's important that the other process sees all the recent writes.

  2. If the writing process might crash, and it's important that no writes to the file get lost.

  3. If you're writing to the console, and need to make sure that every message is shown as soon as it's written.

Barren answered 29/3, 2012 at 14:22 Comment(1)
Another question title that has very little to do with the question, yet has nearly 5K viewsUtmost
E
0

The second option is better to use, as it will create an autoflushable PrintWriter object. And if you use first case, then I don't think flush() is required in your example case.

Ehr answered 29/3, 2012 at 14:23 Comment(0)
E
0

Close method flushes before closing. If you use close(), flush() is not necessary in your first and second example (except u wanna use flush before closing).

On top of that your second example also flushes automatically when using the methods: println, printf, or format

Eada answered 21/6, 2023 at 9:4 Comment(1)
This question is fairly old and already has an accepted answer. How does your answer improve the previous accepted answer?Swiss

© 2022 - 2024 — McMap. All rights reserved.