1

I have read following topic: Should one call .close() on HttpServletResponse.getOutputStream()/.getWriter()?

But what if I use following construction:

    ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());

Should I close it or container will do it instead of me?

gstackoverflow
  • 36,709
  • 117
  • 359
  • 710
  • The javadoc for `ZipOutputStream.close()` says "Closes the ZIP output stream as well as the stream being filtered." . – Arnaud Sep 25 '17 at 08:29
  • @Berger, yes, it closes. But container will close only response.getOutputStream() ans will not close ZipOutputStream – gstackoverflow Sep 25 '17 at 08:40

2 Answers2

2

Yes, you should call close() method on ZipOutputStream explicitly, here's the code for close() method. It does the following:

  • Call close() of super class, which is DeflaterOutputStream in our case
  • close() of DeflaterOutputStream calls finish() before calling close() on underlying OutputStream.

This finish() method writes the remaining compressed data so you might end up with some unwritten data if you do not call close() on ZipOutputStream explicitly. So, I would recommend calling it.

Darshan Mehta
  • 30,102
  • 11
  • 68
  • 102
1

Generally speaking the closing the outermost stream will propagate the close() to inner streams, closing all required resources.

It's of course perfectly possible to create a badly behaving stream, but ZipOutputStream probably isn't one.

In some cases it may not be enough to call close() on the outermost stream, but the documentation for the class should indicate any special behaviour.

Kayaman
  • 72,141
  • 5
  • 83
  • 121