• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Closing Chained Streams

 
Drew Lane
Ranch Hand
Posts: 296
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If I do something like this:

InputStream is = con.openInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
MyBufferedInputSream mybis = new BufferedInputStream(bis);

etc., etc.

Can I just close the last stream (mybis) or should I close each one?

What if I just close the original InputStream (is)? Will all the other streams close and get cleaned up by the garbage collector?

Thanks!

Drew
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You should always close the outermost stream (in this case, mybis), and close it before any others. Closing the other stream after that is optional - you con't really need to because the each outer stream will close the next stream inside it. But if you want to close the inner streams too, that doesn't do any harm. If you close inner streams before outer streams though, you may get an exception. That's particularly true for output streams.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic