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 256-byte buffer is used to try to make the reads efficient. A main() method provides a simple test for this class by reading from System.in and copying to System.out.

Example 3-3. The StreamCopier Class

package com.macfaq.io;
import java.io.*;

public class StreamCopier {

  public static void main(String[] args) {
    try {

    }
    catch (IOException e) {System.err.println(e);}
  }

  public static void copy(InputStream in, OutputStream out) 
   throws IOException {

    // Do not allow other threads to read from the input
    // or write to the output while copying is taking place
    synchronized (in) {
      synchronized (out) {
        byte[] buffer = new byte[256];
        while (true) {
          int bytesRead = in.read(buffer);
          if (bytesRead == -1) break;
          out.write(buffer, 0, bytesRead);
        }
      }
    }
  }
}

Here’s a simple test run:

D:\JAVA\ioexamples\03>java com.macfaq.io.StreamCopier
this is a test
this is a test
0987654321
0987654321
^Z

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

Get Java I/O now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.