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
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
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.
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.
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();
}
}
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.