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
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access