I'm trying to use zlib in Java (java.util.zip) to zip a file, but cannot unzip the file after creating it. I'm using the code below:
public static ByteArrayInputStream compress(InputStream inputStream, String targetFilePath) {
String fileName = new File(targetFilePath).getName();
try {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ZipOutputStream zipOutputStream = new ZipOutputStream(byteArrayOutputStream);
zipOutputStream.putNextEntry(new ZipEntry(fileName));
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
byte[] buffer = new byte[1000];
int len;
while ((len = bufferedInputStream.read(buffer)) > 0) {
zipOutputStream.write(buffer, 0, len);
}
bufferedInputStream.close();
zipOutputStream.closeEntry();
return new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
} catch (IOException ex) {
log.error("The file does not exist");
}
return null;
}
When I read a sample.txt file, and input it as an InputStream to this method, it creates a sample.zip file.
However, when I try to open this zip file using unzip command, it fails to open with the error below:
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 sample.zip or
sample.zip.zip, and cannot find sample.zip.ZIP, period.
I tried opening the zip using jar xvf sample.zip which worked and showed to contain the sample.txt text file. This works because jar command does not look for the End-of-central-directory signature in the zip file.
Could someone shed some light as to why this signature is not there in the zip file? Any help in this regard is much appreciated.