Reputation: 1550
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?
Upvotes: 0
Views: 2009
Reputation: 21
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.
Upvotes: 0
Reputation: 2824
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.
Upvotes: 1