Java - Zip output stream dynamic buffer size

5k views Asked by At

I'm working on application that takes files from one zip and put them in the other, its fine with files but if there is a dir in the source zip it fail with the following exception:

Exception in thread "main" java.util.zip.ZipException: invalid entry size (expected 1374 but got 1024 bytes)

I'm using the following code:

public static void ZipExtractToZip(File inZip, File outZip) throws IOException
{
    ZipInputStream zis = new ZipInputStream(new FileInputStream(inZip));
    ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(outZip)));
    byte[] buffer = new byte[1024];

    for (ZipEntry ze = zis.getNextEntry(); ze != null; ze = zis.getNextEntry()) 
    {
        zos.putNextEntry(ze);
        for (int read = zis.read(buffer); read != -1; read = zis.read(buffer)) {
            zos.write(buffer, 0, read);
        }
        zos.closeEntry();
    }

    zos.close();
    zis.close();
}

I have tried different buffer sizes but that doesn't help, I need a way to get a dynamic buffer size. Examples and links are welcome.

EDIT: I changed the code to make it usable

1

There are 1 answers

4
Peter Lawrey On BEST ANSWER

Move

zos.closeEntry();

outside the inner most loop, otherwise you are assuming each entry is no more than 1024 bytes long.

I am guess your directory is the first entry to be that size.


BTW, You can also move

byte[] buffer = new byte[1024];

to before the outer loop so it is created only once.