Sunday, 12 August 2012

How to Silently Close Resources in Java?

The following piece of code describes how to silently and properly close a stream resource in Java:
File f = new File("SomeFile.txt");
FileOutputStream fos = null;

try {

    fos = new FileOutputStream(f);<

    // Do something...

} catch (FileNotFoundException ex) {

    // Display error message

} finally {

    // Closing resource
    if ( fos != null )  {

        try {

            fos.close();

        } catch (IOException ex) {

            // Silently ignore it

        }

    }

}
Yet, the amount of code required to close each stream in finally is nothing but clutter which does not help with readability too. Fortunately, the Apache Commons library offers a tool solving this issue:
} finally {

    IOUtils.closeQuietly(out);

}