ZipOutputStream - closeEntry() first or close() fi

2019-08-13 06:59发布

问题:

Following is part of the some code. I need to close out resources in finally clause. Do I need to call closeEntry() first or close()? I am getting some error messages.

Error closing the zipoutjava.io.IOException: Stream closed at 
  java.util.zip.ZipOutputStream.ensureOpen(ZipOutputStream.java:70) at 
  java.util.zip.ZipOutputStream.closeEntry(ZipOutputStream.java:189)

The code

 ZipOutputStream zos = null;

  try{

    ZipEntry entry = new ZipEntry("file.csv")
    zipout.putNextEntry(entry);
            csvBeanWriter = new CsvBeanWriter(writer,
                    CsvPreference.STANDARD_PREFERENCE);
            csvBeanWriter.writeHeader(header);
            for (Book book : bookList) {
                csvBeanWriter.write(book, header);
                csvBeanWriterTest.write(book, header);

            }

        } catch (Exception e) {
            logger.error("Export of package data failed: "
                    + e);

        } finally {

            if (zipout != null) {
                try {
                    zos.closeEntry();
                    zos.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    logger.error("Error closing the zos"
                            + e);
                }
            }
}

回答1:

Consider the scheme of using zipout:

zipout = // open zipout someway
// do something with it
zipout.close();

So, it the block, where we do something with zipout you should create and close entries:

ZipEntry z = ...
// do something with it
zipout.closeEntry();

The resulting scheme is:

zipout = ...

ZipEntry z1 = ...
zipout.putNextEntry(z1);
// write something to zipout
zipout.closeEntry();

ZipEntry z2 = ...
zipout.putNextEntry(z2);
// write something to zipout
zipout.closeEntry();

//...

ZipEntry zN = ...
zipout.putNextEntry(zN);
// write something to zipout
zipout.closeEntry();


zipout.close();

So, you should firstly close entry, then zipout.

Example code: https://community.oracle.com/thread/2097141?start=0



回答2:

ZipOutputStream#closeEntry() closes the current entry in the zip file, and because you only have one entry it isn'y that big of a deal. If you need to put another entry in you just have to close the current entry first before putting the next one in.

ZipOutputStream#close() closes the file stream completely, use this when you are done adding stuff to your stream.

TL;DR Put the closeEntry() first if you use it, I don't know if its even necessary to close the last entry in this type of OutputStream.