• Post Reply Bookmark Topic Watch Topic
  • New Topic

Does the order of stream closing matters?  RSS feed

 
sumit anand kumar
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

Could you please look into this code below, and let me know if closing ByteArrayOutputStream before ObjectOutputStream is a problem.
If yes, then what problems i will land into doing this. And the same for ByteArrayInputStream + ObjectInputStream

 
Rob Spoor
Sheriff
Posts: 21052
85
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the case of ByteArrayOutputStream it doesn't matter. Closing it doesn't do anything. For other sub classes of OutputStream the order is very important. When an ObjectOutputStream is closed it writes some extra data to its underlying OutputStream. If you close that stream first though, it will fail with an exception.

However, and this is good news, you usually don't need to worry about that. As far as I know, all sub classes of InputStream and OutputStream that use an underlying InputStream / OutputStream close that underlying stream when it's closed itself. Therefore, if you close your ObjectOutputStream, it will close the ByteArrayOutputStream as well. Likewise for the input streams.
 
Aditya Jha
Ranch Hand
Posts: 227
Eclipse IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To add to what Rob has explained... please note that the wrapper output stream (like ObjectOutputStream) may have some buffered data, yet to be written to the wrapped stream. Usually, the last bit of leftover data is flushed while closing the stream. So, if you happen to close the wrapped stream first, you might simply lose it (even if you don't encounter an IOException, that is).

Thumb rule - Just close the outermost streams, and they will have a cascading effect on the wrapped ones.
 
sumit anand kumar
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Rob & Aditya
 
Rob Spoor
Sheriff
Posts: 21052
85
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!