Diyarbakir
Diyarbakir

Reputation: 2099

Closing InputStream without a try/catch block?

I know that an InputStream should be closed. But I have some doubts where and how to do this.

According to the documentation on IOUtils.closeQuietly:

Unconditionally close an InputStream. Equivalent to InputStream.close(), except any exceptions will be ignored. This is typically used in finally blocks.

I don't need a try/catch block in my code so I don't have a finally block. Is it fine to just close the InputStream before returning it in my method below or should I do something differently? This method will be used by several services to load an InputStream from a file.

public InputStream read(String filename) {
    InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(filename);

    if (inputStream == null) {
      // Throw some exception
    }

    IOUtils.closeQuietly(inputStream);

    return inputStream;
}

Upvotes: 2

Views: 8253

Answers (2)

Ashish Patel
Ashish Patel

Reputation: 159

try/finally block:

InputStream is = null; try { InputStream is = is = read(filename); // Do whatever with is. } finally { is.close(); }

Note: all i/o resources need to be closed in the finally block since it was initialized in the try-catch block. It is also advised to add:

} catch(IOException e){
   e.printstacktrace();
}

...for exception handling

Upvotes: 0

Andy Turner
Andy Turner

Reputation: 140534

You shouldn't be calling IOUtils.closeQuietly(inputStream); at all in this method - there is very little point in returning a closed stream.

However, this method should be called in a try/finally block:

InputStream is = null;
try {
  is = read(filename);
  // Do whatever with is.
} finally {
  IOUtils.closeQuietly(is);
}

or with try-with-resources (noting the comment here that "try-with-resources statement will eliminate most needs for using IOUtils.closeQuietly"):

try (InputStream is = read(filename)) {
  // Do whatever with is.
}

Upvotes: 8

Related Questions