1

I'm writing a code with Java7 and I use the try-with-resources feature. When I create an instance of ZipOutputStream. By doing that I no longer have to close the stream in the finally block. The try-with-resources managed that (by the JVM of course).
My question is - what about the use of closeEntry(). Should I write this method in my try block or should I delete it and the JVM will close it automatically by the try-with-resources feature just like it does with the method close()?

I'm almost sure that it is not relevant to the try-with-resources (or to the finally block) and I should do it inside my try block and not in the finally block (if I use a regular try-catch-finally), but I want to be sure about it.

Thanks!!!

1 Answers1

1

what about the use of closeEntry(). Should I write this method in my try block or should I delete it and the JVM will close it automatically by the try-with-resources feature just like it does with the method close()?

If you want closeEntry() to be invoked, then you should arrange for it to be invoked. It will not be invoked automatically when the try-with-resources block is exited -- at least not directly. Nor should it be, for closeEntry() logically pairs with putNextEntry(), and entering the body of the try block does not cause putNextEntry() to be invoked.

It is possible that stream closure will subsume the effect of closeEntry() if, in fact, an entry is open when it is invoked. That is not documented, however, so the safest thing to do would be to indeed ensure that closeEntry() is invoked after the last entry. You may also invoke it between entries, but you do not need to do so because putNextEntry() is documented to close any open entry before starting a new one.

John Bollinger
  • 160,171
  • 8
  • 81
  • 157