Closing Java InputStreams

I would go with a try-with-resources (at least for Java 7+):

Properties props = new Properties();

try(InputStream fis = new FileInputStream("message.properties")) {
    props.load(fis);
    //omitted.
} catch (Exception ex) {
    //omitted.
}

The close() call should be automatically called when the try block is exited.


The Properties class wraps the input stream in a LineReader to read the properties file. Since you provide the input stream, it's your responsibility to close it.

The second example is a better way to handle the stream by far, don't rely on somebody else to close it for you.

One improvement you could make is to use IOUtils.closeQuietly()

to close the stream, e.g.:

Properties props = new Properties();
InputStream fis = new FileInputStream("message.properties");
try {
    props.load(fis);
    //omitted.
} catch (Exception ex) {
    //omitted.
} finally {
    IOUtils.closeQuietly(fis);
}