comatose
comatose

Reputation: 1962

Closing inputstreams in Java

I have the following piece of code in a try/catch block

 InputStream inputstream = conn.getInputStream();
 InputStreamReader inputstreamreader = new  InputStreamReader(inputstream);
 BufferedReader bufferedreader = new BufferedReader(inputstreamreader);

My question is that when I have to close these streams in the finally block, do I have to close all the 3 streams or just closing the befferedreader will close all the other streams ?

Upvotes: 28

Views: 11446

Answers (6)

Fabian Barney
Fabian Barney

Reputation: 14549

Normally it is ok to just close the most outer stream, because by convention it must trigger close on the underlying streams.

So normally code looks like this:

BufferedReader in = null;

try {
    in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    ...
    in.close(); // when you care about Exception-Handling in case when closing fails
}
finally {
    IOUtils.closeQuietly(in); // ensure closing; Apache Commons IO
}

Nevertheless there may be rare cases where an underlying stream constructor raises an exception where the stream is already opened. In that case the above code won't close the underlying stream because the outer constructor was never called and in is null. So the finally block does not close anything leaving the underlying stream opened.

Since Java 7 you can do this:

    try (OutputStream out1 = new ...; OutputStream out2 = new ...) {
        ...
        out1.close(); //if you want Exceptions-Handling; otherwise skip this
        out2.close(); //if you want Exceptions-Handling; otherwise skip this            
    } // out1 and out2 are auto-closed when leaving this block

In most cases you do not want Exception-Handling when raised while closing so skip these explicit close() calls.

Edit Here's some code for the non-believers where it is substantial to use this pattern. You may also like to read Apache Commons IOUtils javadoc about closeQuietly() method.

    OutputStream out1 = null;
    OutputStream out2 = null;

    try {
        out1 = new ...;
        out2 = new ...;

        ...

        out1.close(); // can be skipped if we do not care about exception-handling while closing
        out2.close(); // can be skipped if we ...
    }
    finally {
        /*
         * I've some custom methods in my projects overloading these
         * closeQuietly() methods with a 2nd param taking a logger instance, 
         * because usually I do not want to react on Exceptions during close 
         * but want to see it in the logs when it happened.
         */
        IOUtils.closeQuietly(out1);
        IOUtils.closeQuietly(out2);
    }

Using @Tom's "advice" will leave out1 opened when creation of out2 raises an exception. This advice is from someone talking about It's a continual source of errors for obvious reasons. Well, I may be blind, but it's not obvious to me. My pattern is idiot-safe in every use-case I can think of while Tom's pattern is error-prone.

Upvotes: 8

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147144

You only need to close the actual resource. You should close the resource even if constructing decorators fails. For output, you should flush the most decorator object in the happy case.

Some complications:

  • Sometimes the decorators are different resources (some compression implementations use the C heap).
  • Closing decorators in sad cases actually causes flushes, with ensuing confusion such as not actually closing the underlying resource.
  • It looks like you underlying resource is a URLConnection, which doesn't have a disconnect/close method as such.

You may wish to consider using the Execute Around idiom so you don't have to duplicate this sort of thing.

Upvotes: 0

Tudor
Tudor

Reputation: 62439

Closing the outermost one is sufficient (i.e. the BufferedReader). Reading the source code of BufferedReader we can see that it closes the inner Reader when its own close method is called:

513       public void close() throws IOException {
514           synchronized (lock) {
515               if (in == null)
516                   return;
517               in.close();
518               in = null;
519               cb = null;
520           }
521       }
522   }

Upvotes: 3

João Rocha da Silva
João Rocha da Silva

Reputation: 4309

I would close all of them in the inverse order from which you have opened them, as if when opening them would push the reader to a stack and closing would pop the reader from the stack.

In the end, after closing all, the "reader stack" must be empty.

Upvotes: 0

Andres Olarte
Andres Olarte

Reputation: 4380

As a rule of thumb, you should close everything in the reverse order that you opened them.

Upvotes: 0

casablanca
casablanca

Reputation: 70701

By convention, wrapper streams (which wrap existing streams) close the underlying stream when they are closed, so only have to close bufferedreader in your example. Also, it is usually harmless to close an already closed stream, so closing all 3 streams won't hurt.

Upvotes: 31

Related Questions