简体   繁体   中英

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM