When / why to call System.out.flush () in Java

Why do some streams need to be cleared ( FileOutputStream and streams from sockets) while the standard output stream does not work?

Every time someone uses the System.out object, whether they are by calling println() or write() , they never clear the stream. However, other programmers usually call flush() a PrintStream / PrintWriter other threads.

I recently asked this question to several programmers, and some believe that there is some background image processing in Java to automatically clear the System.out stream, but I can not find the documentation for this question.

Something like this makes me wonder if just calling System.out.println() platform independent, as you might need some systems to clear the stream.

+48
java
Aug 23 '11 at 19:17
source share
4 answers

System.out based on PrintStream , which by default is reset whenever a new line is written.

From javadoc :

autoFlush - logical; if true, the output buffer will be flushed whenever an array of bytes is written, one of the println methods is called, or a newline or byte character is written ( '\n' )

Thus, the println case you described is explicitly handled, and the write case with byte[] also guaranteed to be cleared, because it falls under "whenever the byte array is written."

If you replace System.out with System.setOut and don’t use the autocomplete stream, then you will need to clear it like any other stream.

The library code probably should not use System.out directly, but if it is, then it should be careful because the library user can override System.out to use the stream without clearing it.

Any Java program that writes binary output to System.out should be careful until flush before exit , because binary output often does not include a terminating new line.

+49
Aug 23 '11 at 19:19
source share
β€” -

From the PrintStream documentation :

Optionally, a PrintStream can be created to automatically change; this means that the flush method is automatically called after writing a byte array, one of the println methods is called, or a newline or byte character ( '\n' ) is written.

Although I do not see any explicit mention in it, I understand that System.out will do this automatic flushing.

+6
Aug 23 '11 at 19:21
source share

If you cannot wait for the item to appear, flush the stream.

When the JVM goes down, rather than flushing the stream, it runs the risk of losing an item in the display buffer, which can make a reasonable error message telling you why the JVM was lost forever. This makes debugging much more difficult, as people then tend to say: "but she didn’t get here because she would print it."

+4
Aug 23 '11 at 19:21
source share

System.out defaults to line buffering. Therefore, if you call println rather than print , this should not be a problem. See this article for more details.

+2
Aug 23 '11 at 19:20
source share



All Articles