I am wondering the purpose of BufferedOutputStream, performance gain when using it?
Creates a new buffered output stream to write data to the specified underlying output stream with the specified buffer size.
BufferedInputStream and BufferedOutputStream use an internal array of byte, also known as buffer, to store data while reading and writing, respectively.
BufferedOutputStream is a class in Java which we can use to write data into the output stream. It uses a buffer to write data instead of directly writing into the file. We can use the FileOutputStream class along with the BufferedOutputStream to write information to the file.
Buffered input streams read data from a memory area known as a buffer; the native input API is called only when the buffer is empty. Similarly, buffered output streams write data to a buffer, and the native output API is called only when the buffer is full.
Here is the line from API of BufferedOutputStream:
The class implements a buffered output stream. By setting up such an output stream, an application can write bytes to the underlying output stream without necessarily causing a call to the underlying system for each byte written.
It can do most of operations within the buffer, and without a call to the underlying system.
For example, consider writing to file: without buffer, it has to make a system call for every single byte, which is obviously slow.
As its name suggests, BufferOutputStream
has an internal buffer (byte[]
) to which contents of individual small writes are first copied. They are written to the underlying OutputStream
when buffer is full, or the stream is flushed, or the stream is closed.
This can make a big difference if there is a (relatively large) fixed overhead for each write operation to the underlying OutputStream
, as is the case for FileOutputStream
(which must make an operating system call) and many compressed streams.
At the same time, many stream-based libraries use their own buffering (like XML and JSON writers), and use of BufferedOutputStream
provides no benefit. But its own overhead is relatively low so there isn't much risk.
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