Many output streams buffer writes to improve performance. Rather than
sending each byte to its destination as it’s written, the bytes
are accumulated in a memory buffer ranging in size from several bytes
to several thousand bytes. When the buffer fills up, all the data is
sent at once. The
flush()
method forces the data to be written whether or not the buffer is
full:
public void flush() throws IOException
This is not the same as any buffering performed by the operating
system or the hardware. These buffers will not be emptied by a call
to flush()
. (Then sync()
method
in the FileDescriptor
class, discussed in Chapter 12, can sometimes be used to empty these buffers.) For example,
assuming out is an OutputStream
of some sort, you
would call out.flush()
to empty the buffers.
If you only use a stream for a short time, you don’t need to
flush it explicitly. It should be flushed when the stream is closed.
This should happen when the program exits or when you explicitly
invoke the
close()
method:
public void close() throws IOException
For example, again assuming out
is an
OutputStream
of some sort, calling
out.close()
closes the stream and implicitly
flushes it. Once you have closed an output stream, you can no longer
write to it. Attempting to do so will throw an
IOException
.
Again, System.out
is a
partial exception because as a PrintStream
, all
exceptions it throws are eaten. Once you close
System.out
, you can’t write to it, but
trying to do so won’t throw any exceptions. However, your
output will not appear on the console.
You only need to flush an output stream explicitly if you want to make sure data is sent before you’re through with the stream. For example, a program that sends a burst of data across the network periodically should flush after each burst of data is written to the stream.
Flushing is often important when you’re trying to debug a
crashing program. All streams flush automatically when their buffers
fill up, and all streams should be flushed when a program terminates
normally. If a program terminates abnormally, however, buffers may
not get flushed. In this case, unless there is an explicit call to
flush()
after each write, you can’t be sure
the data that appears in the output indicates the point at which the
program crashed. In fact, the program may have continued to run for
some time past that point before it crashed.
System.out
, System.err
, and
some (but not all) other print streams automatically flush after each
call to println()
and after each time a new line
character ('
'
) appears in the string being
written. Whether auto-flushing is enabled can be set in the
PrintStream
constructor.
18.188.96.5