Thursday 15 March 2018

Zip file is invalid for file zipped using ZipOutputStream

Are you seeing an error like below when you try to unzip a file which was zipped using the java.util.zip.ZipOutputStream




Or are you seeing an error like below when you unzip from Linux

unzip myfile.zip 
Archive:  myfile.zip 
  End-of-central-directory signature not found.  Either this file is not 
  a zipfile, or it constitutes one disk of a multi-part archive.  In the 
  latter case the central directory and zipfile comment will be found on 
  the last disk(s) of this archive. 
unzip:  cannot find zipfile directory in one of 
myfile.zip or 
        myfile.zip.zip, and cannot find 
myfile.ZIP, period.


If the answer is YES, then check how you are closing the ZipOutputStream in your code. The ZipOutputStream should be closed before calling the toByteArray() of your ByteArrayOutputStream


ByteArrayOutputStream baos = new ByteArrayOutputStream();
try(ZipOutputStream zos = new ZipOutputStream(baos);) {
zip(zos, incidentDir, incidentDir);
zos.flush();
baos.flush();
}
catch (Exception e) {                
throw new Exception("Unable to Zip the folder");
}
byte[] result = baos.toByteArray();


The documentation of ByteArrayOutputStream says
The methods in this class can be called after the stream has been closed without generating an IOException.
https://docs.oracle.com/javase/8/docs/api/java/io/ByteArrayOutputStream.html