The following piece of code describes how to silently and
properly close a stream resource in Java:
File f = new File("SomeFile.txt");
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);
}
finally {
IOUtils.closeQuietly(out);