Disposing streams in Java

java, stream

Solution

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).

Problem

In C#, I almost always use the `using` pattern when working with stream objects. For example: ``` using (Stream stream = new MemoryStream()) { // do stuff } ``` By using the `using` block, we ensure that dispose is called on the stream immediately after that code bock executes. I know Java doesn't have the equivalent of a `using` keyword, but my question is that when working with an object like a `FileOutputStream` in Java, do we need to do any housekeeping to make sure it gets disposed? I was looking at this code example, and I noticed they don't do any. I just wondered what the best practice was for Java in handling disposing streams, or if it's good enough to let the garbage collector handle it.

Original source