Disposing streams in Java

The feature you want was indeed introduced in Java 7, under the name "try-with-resources statement" (also known as automatic resource management (ARM)). Here is the code:

try (InputStream in = new FileInputStream("foo.txt")) {
    ...
}  // This finally calls in.close()

generally, you have to do the following:

InputStream stream = null;
try {
   // IO stuff - create the stream and manipulate it
} catch (IOException ex){
  // handle exception
} finally {
  try {
     stream.close();
  } catch (IOException ex){}
}

But apache commons-io provides IOUtils.closeQuietly(stream); which is put in the finally clause to make it a little less-ugly. I think there will be some improvement on that in Java 7.

Update: Jon Skeet made a very useful comment, that the actual handling of the exception is rarely possible to happen in the class itself (unless it is simply to log it, but that's not actually handling it). So you'd better declare your method throw that exception up, or wrap it in a custom exception (except for simple, atomic operations).

Tags:

Java

Stream