Flushing and Closing Output Streams

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.

Note

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 ...

Get Java I/O now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.