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

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.

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( ).

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( ).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.31.67