permaculture playing cards
The moose likes I/O and Streams and the fly likes Closing Chained Streams Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "Closing Chained Streams" Watch "Closing Chained Streams" New topic

Closing Chained Streams

Drew Lane
Ranch Hand

Joined: May 13, 2001
Posts: 296
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?


Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
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'm not back." - Bill Harding, Twister
I agree. Here's the link:
subject: Closing Chained Streams
It's not a secret anymore!