my question is in some way similar to this one: what's the purpose of BufferedOutputStream? I have read the answers there, but there is still one thing I do not really understand: So in Java a BufferedOutputStream has an internal buffer. And if this buffer is full or flush() is called, it writes the data to the underlying OutputStream (the one that was passed to the BufferedOutputStream's constructor). So far ok. But for me it looks, as if in fact any OutputStream would have such a buffer - as the base class OutputStream has a method flush(). The description of this method sais: "Flushes this output stream and forces any buffered output bytes to be written out." So ... if all OutputStreams have a buffer, what is the benefit of a BufferedOutputStream then? Probably I am misunderstanding something ... can you please help me?
Greetings, Daniel
The base class OutputStream
is abstract. Meaning it defines the interface and some common behavior of all output streams. You cannot instantiate OutputStream
instance.
The documentation clearly states that
The flush method of OutputStream does nothing.
It is up to the concrete implementation to determine whether or not it uses a buffer.
OutputStream has no buffer, you can check source code. BufferedOutputStream has its own buffer, its flush() writes bytes from own buffer to OS then flushes OS buffer. Why using BufferedOutputStream is more efficient - because OutputStream.write may call OS each time, which is expensive operation, and BufferedOutputStream.write puts bytes to buffer and calls OS only when buffer is full or on flush
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.