Filter Streams   «Prev  Next»

Lesson 5Optimizing performance with buffered streams
ObjectiveWrite a Program that performs a Buffered File Copy in Java

Write a Program that performs a Buffered File Copy in Java

Buffered Input Streams

Buffered input streams read more data than they initially need into a buffer. When the stream's read methods are invoked, the data is removed from the buffer rather than from the underlying stream. When the buffer runs out of data, the buffered stream refills its buffer from the underlying stream. In situations where it is almost as fast to read 500 bytes of data as it is to read 1 byte, this is a significant performance gain.

Buffered Output Streams

Buffered output streams store data in an internal byte array until the buffer is full, or until the stream is flushed. Then the data is written out to the underlying output stream in one swoop. Again, one big write of many bytes is usually as fast or faster than many small writes that add up to the same thing.

Constructors


BufferedInputStream and BufferedOutputStream each have two constructors.
public BufferedInputStream(InputStream in)

public BufferedInputStream(InputStream in, int size)

public BufferedOutputStream(OutputStream out)

public BufferedOutputStream(OutputStream out, int size)


The first argument is the underlying stream from which data will be read or to which data will be written. The size argument is the number of bytes in the buffer. If a size is not specified, a 2,048 byte buffer is used.

Buffer size

The best size for the buffer is highly platform-dependent and generally related to the block size of the disk, at least for file streams. Less than 512 bytes is probably too little and more than 4,096 bytes is probably too much. Ideally you want an integral multiple of the block size of the disk. However, you should use smaller buffer sizes for unreliable network connections.
Here is an example of using a 256-byte buffer:

URL u = new URL("http://java.developer.com");
BufferedInputStream bis = new BufferedInputStream(u.openStream(), 256);

Buffered Streams- Exercise

Click the Exercise link below to write a program that copies files named on the command line to System.out with buffered reads and writes.
Buffered Streams - Exercise

Java I/O