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 and copying to System.out.

Example 3-3. The StreamCopier Class


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 =;
          if (bytesRead == -1) break;
          out.write(buffer, 0, bytesRead);

Here’s a simple test run:

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 in Windows, the end-of-stream character is Ctrl-Z. On Unix it would have been Ctrl-D.

Get Java I/O now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.