简体   繁体   中英

JAVA - Corrupt ZIP file using ZipOutptuStream with FileInputStream

Why might the following code be generating a corrupt zip file when output over a servlet output stream? When writing the ZIP to disk locally using a FileOutputStream, the output stream does not appear to be corrupt.

// Create zip stream
ZipOutputStream zos = new ZipOutputStream(this.servletOutputStream);

// prepare a new entry
ZipEntry zipEntry = new ZipEntry(forZip.getName());
zipEntry.setSize(forZip.getTotalSpace());
zipEntry.setTime(System.currentTimeMillis());

// write entry
zos.putNextEntry(zipEntry);

// write the file to the entry
FileInputStream toBeZippedInputStream = new FileInputStream(forZip);
IOUtils.copy(toBeZippedInputStream, zos);
zos.flush();

// close entry
zos.closeEntry();

// close the zip
zos.finish();
zos.close();

this.servletOutputStream.flush();

this.servletOutputStream.close();

// close output stream
IOUtils.closeQuietly(toBeZippedInputStream);

Is this perhaps an issue with order of flushing/closing streams?

Try closing the zip entry before flushing the zip stream

// close entry
zos.closeEntry();

zos.flush();

On the coding style, use try-with-resources to make sure the resources are closed properly.

A potential problem I see is that the individual entries to be zipped are not unique. If you are looping through in this code, forZip.getName() may have duplicates.

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