1

I'm reading a file containing binary data followed by a serialized object:

FileInputStream fis = new FileInputStream(file);
GZIPInputStream gzis = new GZIPInputStream(fis);
DataInputStream dis = new DataInputStream(gzis);
ObjectInputStream ois = new ObjectInputStream(gzis);
int i = dis.readInt();
Object o = ois.readObject();

While writing this code some questions came to mind:
1. Which streams should be closed?
2. How to correctly handle exceptions without try-finally spaghetti?

DutChen18
  • 1,133
  • 1
  • 7
  • 24
  • Have you heard of the [`try-with-resources` statement](https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html)? – Sweeper Apr 30 '20 at 15:05
  • Does [this](https://stackoverflow.com/questions/30553139/close-multiple-resources-with-autocloseable-try-with-resources) answer your questions? – Sweeper Apr 30 '20 at 15:07
  • @Sweeper yes i have, and it would work assuming it's ok to close all the streams. However i usually only see the outermost stream being closed, as it already closes the stream it encapsulates. This is what confuses me, i have two outermost streams, closing both would close the root stream twice, is that bad? – DutChen18 Apr 30 '20 at 16:38
  • 1
    You should probably make what you are asking clear in your question. That is "is closing a stream twice bad?" And since you know about `try-with-resources`, why not just use a `catch` clause after the `try (...) { ... }` to catch exceptions? What's spaghetti about that? – Sweeper Apr 30 '20 at 16:41
  • @Sweeper I believe i did make my question clear enough: "Which streams should be closed?". At this point i assume you're saying closing a stream twice is ok (you should probably make that clear xD), in which case there is no spaghetti, but i can't think of a way to do it cleanly if special care had to be taken to not close the stream twice. – DutChen18 Apr 30 '20 at 17:00

0 Answers0