Skip to content
June 2, 2011 / oop123

Closing java.io Resources

Just a quick post on good Java coding style (using Internet as my source as always). After you finish using a IO resource (IOStream, Reader, etc.), you need to close it with .close() to save system resources. Since you always want .close() to run despite any possible Exception, you would put it in a finally block. Unfortunately, because .close() throws IXException, the code can be pretty ugly:

InputStream in;
try {
   in = new FileInputStream(new File("random.txt"));
   //do stuff with in
}
catch(IOException e) {
    //log
}
finally {
    try {
        in.close();
    } catch(IOException e) {
        //log
    }
}

A better way of doing it is this:

InputStream in;
try {
    try {
        in = new FileInputStream(new File("random.txt"));
        //do stuff with in
    }
    finally {
        in.close();
    }
}
catch(IOException e) {
    //log
}

If you don’t want to handle a IOException, you could implement a utility function to close the IO resource quietly without raising an exception and use it in your code:

public static void closeQuietly(Closeable closeable) {
    try {
        if (closeable != null) {
            closeable.close();
        }
    } catch (IOException e) {}
}

This function can be found in the Apache Commons IO (IOUtils). Note this method should not be used on OutputStreams, as you would want to handle the exception if something went wrong while writing data to a file (or some other places).

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: