Question

I'm creating a zip file with ZipOutputStream using pretty standard code. For some reason when I read it back in as a ZipInputStream the ZipEntry has size=-1. The filename is stored correctly in the ZipEntry.

(When I make a zip file using my OS tools and then read it back in, the size is correct, so I assume the problem is with ZipOutputStream and not the ZipInputStream).

The context is a Spring MVC controller.

What am I doing wrong? Thanks.

Here is the code:

// export zip file
String file = "/Users/me/Desktop/test.jpg";
FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream(file+".zip");
ZipOutputStream zos = new ZipOutputStream(fos);
zos.putNextEntry(new ZipEntry("test.jpg"));
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fis.read(buffer)) > 0) {
    zos.write(buffer, 0, bytesRead);
}
zos.closeEntry();
zos.close();
fis.close();

// import same file
String file2 = "/Users/me/Desktop/test.jpg.zip";
FileInputStream fis2 = new FileInputStream(file2);
ZipInputStream zis = new ZipInputStream(fis2);
ZipEntry entry = zis.getNextEntry();
// here: entry.getSize() = -1, zip.buf is an array of zeros... 
// but if I unzip the file on my OS I see that the original file has been zipped...
Was it helpful?

Solution 2

It seems that entry.getSize() is simply unreliable: Why ZipInputStream can't read the output of ZipOutputStream?

The above post provides a suitable workaround.

OTHER TIPS

You have to get the next entry from the stream, like in this example:

http://www.roseindia.net/tutorial/java/corejava/zip/zipentry.html

When you set the size manually, it sure would give you a result, like you've shown "64527". You better have a look at the zip examples. They will give you a clear image. Also: Create Java-Zip-Archive from existing OutputStream

Try something, like this:

        String inputFileName = "test.txt";
        String zipFileName = "compressed.zip";

        //Create input and output streams
        FileInputStream inStream = new FileInputStream(inputFileName);
        ZipOutputStream outStream = new ZipOutputStream(new FileOutputStream(zipFileName));

        // Add a zip entry to the output stream
        outStream.putNextEntry(new ZipEntry(inputFileName));

        byte[] buffer = new byte[1024];
        int bytesRead;

        //Each chunk of data read from the input stream 
        //is written to the output stream
        while ((bytesRead = inStream.read(buffer)) > 0) {
            outStream.write(buffer, 0, bytesRead);
        }

        //Close zip entry and file streams
        outStream.closeEntry();

        outStream.close();
        inStream.close();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top