10.3. Closing Streams, Readers, and Writers

Problem

You need to close an InputStream, OutputStream, Reader, or Writer, and you want to avoid catching an IOException in a finally block.

Solution

Use IOUtils.closeQuietly() to close an InputStream, OutputStream, Reader, or Writer without having to test for null or deal with an IOException. The following code demonstrates the use of closeQuietly( ) to avoid a nasty try/catch within a finally block:

import org.apache.commons.io.IOUtils
import org.apache.commons.io.CopyUtils

Reader reader = null;
String result = "":

try {
    File file = new File( "test.dat" );
    reader = new FileReader( file );
    result = CopyUtils.toString( reader );
} catch( IOException ioe ) {
    System.out.println( "Unable to copy file test.dat to a String." );
} finally {
    IOUtils.closeQuietly( reader );
}

Discussion

It is always a good idea to close streams, readers, and writers in finally blocks because you can guarantee that a system will release I/O resources even if an exception is thrown. A call to close( ) releases resources associated with the stream, but because close( ) can throw an IOException , you need to either surround your call to close( ) with a try/catch block, or declare that your method throws an IOException. This problem is best illustrated by the following code, which closes a Reader and Writer without the help of IOUtils:

Reader reader = null; Writer writer = null; String result = "": try { File file = ew File("test.dat"); reader = new FileReader( ...

Get Jakarta Commons Cookbook 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.