gstackoverflow
gstackoverflow

Reputation: 37014

Should I explicitly close ZipOutputStream over response.getOutputStream()?

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?

Upvotes: 3

Views: 1712

Answers (2)

Darshan Mehta
Darshan Mehta

Reputation: 30849

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.

Upvotes: 4

Kayaman
Kayaman

Reputation: 73578

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.

Upvotes: 1

Related Questions