Common Java Cookbook

Edition: 0.19

Download PDF or Read on Scribd

Download Examples (ZIP)

10.2. Copying Streams, byte[ ], Readers, and Writers

10.2.1. Problem

You need to copy a stream, byte[], Reader, or Writer. For example, you need to copy the content from an InputStream or Reader to a Writer, or you need to copy a String to an OutputStream.

10.2.2. Solution

Use CopyUtils from Commons IO to copy the contents of an InputStream, Reader, byte[], or String to an OutputStream or a Writer. The following code demonstrates the use of CopyUtils to copy between an InputStream and a Writer:

import org.apache.commons.io.CopyUtils;
try {
    Writer writer = new FileWriter( "test.dat" );
    InputStream inputStream = 
        getClass( ).getResourceAsStream("./test.resource");
    CopyUtils.copy( inputStream, writer );
    writer.close( );
    inputStream.close( );
} catch (IOException e) {
    System.out.println( "Error copying data" );
}

The previous example reads test.resource using an InputStream, which is copied to a FileWriter using CopyUtils.copy( ).

10.2.3. Discussion

If you need to copy information from a Reader or InputStream to a String, use IOUtils.toString( ). The following example opens an InputStream from a URL and copies the contents to a String:

import org.apache.commons.io.IOUtils;
URL url = new URL( "http://www.slashdot.org" );
try {
    InputStream inStream = url.openStream( );
    String contents = IOUtils.toString( inStream );
    System.out.println( "Slashdot: " + contents );
} catch ( IOException ioe ) {
    // handle this exception
}

Because CopyUtils uses a 4 KB buffer to copy between the source and the destination, you do not need to supply buffered streams or readers to the copy( ) method. When using CopyUtils.copy( ), make sure to flush( ) and close( ) any streams, Readers, or Writers passed to copy( ).


Creative Commons License
Common Java Cookbook by Tim O'Brien is licensed under a Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 United States License.
Permissions beyond the scope of this license may be available at http://www.discursive.com/books/cjcook/reference/jakartackbk-PREFACE-1.html. Copyright 2009. Common Java Cookbook Chunked HTML Output. Some Rights Reserved.