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
On the coding style, use try-with-resources to make sure the resources are closed properly.