tags:

views:

73

answers:

4

In the following code:

DataInputStream in = new DataInputStream(
          new BufferedInputStream(new FileInputStream(file)));
in.close();

do I need to close the 2 other stream in addition to closing the "top level" stream ?

Manu

+5  A: 

if you look the source of DataInputStream you can see that it closes the underlying streams as well. so you don't need. and this is (or should be) true for all type of streams.

KARASZI István
More to the point, it's documented. It's a bit fragmented, but `DataInputStream` inherits `close` from `FilterInputStream`, which documents that it calls `close` on the underlying `InputStream`: http://download.oracle.com/javase/6/docs/api/java/io/FilterInputStream.html So you know that the behavior isn't just a side-effect of a particular implementation.
T.J. Crowder
Actually its true for all types of `Closeable`
Shervin
@Sherwin ... provided that they implement the "contract" properly :-)
Stephen C
+1  A: 

Karazi, is right in suggesting that. Further, just to get an idea and a little more insight, Java IO API is actually implemented using decorator pattern. You can check out decorator pattern on wiki.

Adeel Ansari
+1  A: 

I'd stick the close in a finally block just to make sure it is flushed properly in case of an exception.

public void tryToDoWhatever() throws Exception
{
    DataInputStream in = null;
    try
    {
         in = new DataInputStream(
              new BufferedInputStream(new FileInputStream(file)));
    }
    finally
    { 
        if (in != null)
            in.close();
    }
}
willcodejavaforfood
Yes you are right but this raise a new question: How handle the IOException that can be thrown by in.close ?? Add try catch in finally block or forward it at upper level ?
Manuel Selva
Yes that's not quite hopw I normally do it
willcodejavaforfood
@Manuel Selva - I always separate the exception handling from the business logic. I would have a method called 'doWhatever()' which calls tryToDoWhatever in a try/catch block to deal with the exceptions in there
willcodejavaforfood
+1  A: 

I will use this opportunity to answer with an answer I have already made before.

By using Project Lombok you can let Lombok correctly close the streams for you. Details can be found here.

Shervin