Why do certain streams need to be flushed (FileOutputStream
and streams from Sockets) while the standard output stream does not?
Every time someone uses the System.out
PrintStream
object, be it while calling println()
or write()
, they never flush the stream. However, other programmers habitually call flush()
a PrintStream
/PrintWriter
with other streams.
I've recently asked this question to several programmers and some believe that there is some background handling in Java to auto-flush the System.out
stream but I can't find any documentation on that.
Something like this makes me wonder if simply calling System.out.println()
is platform independent as some systems may need you to flush the stream.
out. flush() to write any data stored in the out buffer. Buffers store text up to a point and then write when full. If you terminate a program without flushing a buffer, you could potentially lose data.
The flush() method of PrintWriter Class in Java is used to flush the stream. By flushing the stream, it means to clear the stream of any element that may be or maybe not inside the stream. It neither accepts any parameter nor returns any value.
The flush() method in Python file handling clears the internal buffer of the file. In Python, files are automatically flushed while closing them. However, a programmer can flush a file before closing it by using the flush() method.
flush() writes the content of the buffer to the destination and makes the buffer empty for further data to store but it does not closes the stream permanently. That means you can still write some more data to the stream. But close() closes the stream permanently.
System.out
is based around a PrintStream
which by default flushes whenever a newline is written.
From the javadoc:
autoFlush - A boolean; if true, the output buffer will be flushed whenever a byte array is written, one of the
println
methods is invoked, or a newline character or byte ('\n'
) is written
So the println
case you mention is explicitly handled, and the write
case with a byte[]
is also guaranteed to flush because it falls under "whenever a byte array is written".
If you replace System.out
using System.setOut
and don't use an autoflushing stream, then you will have to flush it like any other stream.
Library code probably shouldn't be using System.out
directly, but if it does, then it should be careful to flush because a library user might override System.out
to use a non flushing stream.
Any Java program that writes binary output to System.out
should be careful to flush
before exit
because binary output often does not include a trailing newline.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With