An Efficient Stream Copier

As a useful example of both input and output streams, in Example 3-3, I'll present a StreamCopier class that copies data between two streams as quickly as possible. (I'll reuse this class in later chapters.) This method reads from the input stream and writes onto the output stream until the input stream is exhausted. A 1K buffer is used to try to make the reads efficient. A main( ) method provides a simple test for this class by reading from and copying to System.out.

Example 3-3. The StreamCopier class

public class StreamCopier {
 public static void main(String[] args) {
 try {
 copy(, System.out);
 catch (IOException ex) {
 public static void copy(InputStream in, OutputStream out)
 throws IOException {
 byte[] buffer = new byte[1024];
 while (true) {
 int bytesRead =;
 if (bytesRead == -1) break;
 out.write(buffer, 0, bytesRead);

Here's a simple test run:

D:JAVAioexamples3> java
this is a test
this is a test

Input was not fed from the console (DOS prompt) to the StreamCopier program until the end of each line. Since I ran this on Windows, the end-of-stream character is Ctrl-Z. On Unix, it would have been Ctrl-D.

Basic I/O

Introducing I/O

Output Streams

Input Streams

Data Sources

File Streams

Network Streams

Filter Streams

Filter Streams

Print Streams

Data Streams

Streams in Memory

Compressing Streams

JAR Archives

Cryptographic Streams

Object Serialization

New I/O



Nonblocking I/O

The File System

Working with Files

File Dialogs and Choosers


Character Sets and Unicode

Readers and Writers

Formatted I/O with java.text


The Java Communications API


The J2ME Generic Connection Framework


Character Sets

Java I/O
Java I/O
ISBN: 0596527500
EAN: 2147483647
Year: 2004
Pages: 244 © 2008-2020.
If you may any questions please contact us: