Tech and Media Labs
This site uses cookies to improve the user experience.

Java IO: BufferedOutputStream

Jakob Jenkov
Last update: 2015-08-29

The BufferedOutputStream class provides buffering to your output streams. Buffering can speed up IO quite a bit. Rather than write one byte at a time to the network or disk, you write a larger block at a time. This is typically much faster, especially for disk access and larger data amounts.

To add buffering to your OutputStream's simply wrap them in a BufferedOutputStream. Here is how that looks:

OutputStream output = new BufferedOutputStream(
                      new FileOutputStream("c:\\data\\output-file.txt"));

Simple, isn't it?

Setting Buffer Size of a BufferedOutputStream

You can set the buffer size to use internally by the BufferedOutputStream. You provide the size as a constructor parameter, like this:

int bufferSize = 8 * 1024;
OutputStream output = new BufferedOutputStream(
                      new FileOutputStream("c:\\data\\output-file.txt"),

This example sets the internal buffer to 8 KB. It is best to use buffer sizes that are multiples of 1024 bytes. That works best with most built-in buffering in hard disks etc.

Except for adding buffering to your input streams, BufferedOutputStream behaves exactly like an OutputStream. The only difference is that you may need to call flush() if you need to be absolutely sure that the data written until now is flushed out of the buffer and onto the network or disk.

Optimal Buffer Size for a BufferedOutputStream

You should make some experiments with different buffer sizes to find out which buffer size seems to give you the best performance on your concrete hardware. The optimal buffer size may depend on whether you are using the BufferedOutputStream with a disk or network OutputStream.

With both disk and network streams, the optimal buffer size may also depend on the concrete hardware in the computer. If the hard disk is anyways writing a minimum of 4KB at a time, it's stupid to use less than a 4KB buffer. It is also better to then use a buffer size that is a multiple of 4KB. For instance, using 6KB would be stupid too.

Even if your disk writes blocks of e.g. 4KB at a time, it can still be a good idea to use a buffer that is larger than this. A disk is good at writing data sequentially - meaning it is good at writing multiple blocks that are located after each other. Thus, using a 16KB buffer, or a 64KB buffer (or even larger) with a BufferedOutputStream may still give you a better performance than using just a 4KB buffer.

To find the optimal BufferedOutputStream buffer size, find out the block size your hard disk writes in, and make the buffer a multiple of that size. You will definitely have to experiment to find the optimal buffer size. Do so by measuring write speeds with different buffer sizes.

Jakob Jenkov

Copyright  Jenkov Aps
Close TOC