Why do I have to close the ZipOutputStream in a certain way in this situation?

后端 未结 2 1091
無奈伤痛
無奈伤痛 2021-01-07 02:09

I have two examples :

Example 1:

try (ByteArrayOutputStream baous = new ByteArrayOutputStream();     
    FileOutputStream fouscrx = new FileOutputSt         


        
相关标签:
2条回答
  • 2021-01-07 02:20

    ZipOutputStream has to do several operations at the end of the stream to finish the zip file, so it's necessary for it to be closed properly. (Generally speaking, pretty much every stream should be closed properly, just as good practice.)

    0 讨论(0)
  • 2021-01-07 02:30

    Well, it looks like the try-with-resources autoclosing order is important, and the ZipOutputStream has to be closed first when unwinding things. Autoclosing happens in reverse order of their creation in this context.

    What happens if you reorder your second example so the ZipOutputStream is after the FileOutputStream? (Though placing the ZipOutputStream in its own try-catch block is clearer code if you ask me. We separate out the related and unrelated streams and handle the auto-closing in an easily readable manner.)

    UPDATE

    FWIW, this is the sort of idiom I have used in the past when streaming a zip into a buffered output stream:

    try (final ZipOutputStream zip = new ZipOutputStream(new BufferedOutputStream(
                        new FileOutputStream(zipFile.toString())))) { ... }
    
    0 讨论(0)
提交回复
热议问题