3

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

Liam Haworth
  • 848
  • 1
  • 9
  • 27
  • Which line has the exception? BTW: I would use a BufferedInputSTream as well (not that it will fix the issue) – Peter Lawrey Jan 10 '12 at 10:49
  • at java.util.zip.ZipOutputStream.closeEntry(Unknown Source) at com.hachisoftware.mmi.system.Util.ZipExtractToZip(Util.java:26) – Liam Haworth Jan 10 '12 at 10:53

1 Answers1

3

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.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • Thank you, that worked, I got a tiny bit of compression(1kb) but thats ok – Liam Haworth Jan 10 '12 at 11:01
  • Also, if you do this, you only need create the buffer once, outside the outer loop. – sje397 Jan 10 '12 at 11:03
  • 1
    if i was to lower the buffer size would that compress the zip more? – Liam Haworth Jan 10 '12 at 11:08
  • 1
    The stream has its own buffer which is 512 bytes by default. It shouldn't have any effect on compression ratio, only performance. For a normal disk stream a buffer of 8K-64K would be slightly faster, however in your case I doubt it matters (as the compression/decompression is the most expensive) – Peter Lawrey Jan 10 '12 at 11:20