Do all Java output streams have buffers?

Viewed 74

I used OutputStreamWriter with socket. When I tried to write data, I found that the data was not sent out. So I tried the flush() and it succeeded.

I would like to ask some question:

  1. Do all output streams have a buffer ? So is there any unique benefit of a class like BufferedOutputStream? (Since there are buffers)
  2. when I use close(). Has the data in the buffer disappeared or was flushed out? I tested it, the data in the buffer was not successfully written out. But I have seen in many places that calling the close() will flush the data in the buffer?
2 Answers

Not all OutputStream implementations have buffers.

That's trivially proven, since you can just implement your own.

But most uses of an OutputStream will often involve a buffer at some level.

BufferedOutputStream is the obvious candidate, where the buffer is diretly in the class as the primary feature of the class. This way you can add explicit buffering to any other OutputStream.

OutputStreams that communicate with the OS such as FileOutputStream or the OutputStream returned for a network connection don't have explicit buffers themselves, but will write to the OS which may or may not have its own buffer (for example most OS won't immediately write to a file on a write system call and only flush on close or after some time).

In either case (direct buffer in the OutputStream or an underlying system buffer) a flush call tends to initiate a write-back to the "real" target.

Note that a flush before a close should never be necessary on a conforming OutputStream.

Not all OutputStream implementations perform buffering, although buffering is quite a common feature that they had the flush() method defined as part of the contract of OutputStream (specifically by extending a Flushable interface). I think the best source of information about this is the Javadoc of that method:

Flushes this output stream and forces any buffered output bytes to be written out. The general contract of flush is that calling it is an indication that, if any bytes previously written have been buffered by the implementation of the output stream, such bytes should immediately be written to their intended destination.

If the intended destination of this stream is an abstraction provided by the underlying operating system, for example a file, then flushing the stream guarantees only that bytes previously written to the stream are passed to the operating system for writing; it does not guarantee that they are actually written to a physical device such as a disk drive.

The flush method of OutputStream does nothing.

I've highlighted the part where it's clear that it depends on the implementation whether or not buffering is implemented.

Related