Buffered Streams

The java.io.BufferedInputStream and java.io.BufferedOutputStream classes buffer reads and writes by first storing the data in a buffer (an internal array of bytes). Then the program reads bytes from the stream without calling the underlying native method until the buffer is empty. The data is read from or written into the buffer in blocks; subsequent accesses go straight to the buffer.

The only real difference to the programmer between a regular stream and a buffered stream are the constructors:

 public BufferedInputStream(InputStream in)
 public BufferedInputStream(InputStream in, int size)
 public BufferedOutputStream(OutputStream out)
 public BufferedOutputStream(OutputStream out, int size)

The size argument is the number of bytes in the buffer. If a size isn't specified, a 512 byte buffer is used.

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 4096 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.

For example,

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

Previous | Next | Top | Cafe au Lait

Copyright 1997 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified April 7, 1997