JAVA - Corrupt ZIP file using ZipOutptuStream with FileInputStream

1.8k views Asked by At

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?

2

There are 2 answers

1
neurite On BEST ANSWER

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.

1
Dhiren Ghelani On

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.