Lesson 5 | Optimizing performance with buffered streams |
Objective | Write a Program that performs a Buffered File Copy in Java |
Write a Program that performs a Buffered File Copy in Java
InputStream 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