Search code examples
javazippnginputstreamzipoutputstream

Error java.util.zip.ZipException: invalid entry size while copying image (.png) from 1 zip file to another


I'm trying to modify an existing .zip file and then creating a modified copy.

I can easily do that to all files except for a .png file in the zip file, which results in error

java.util.zip.ZipException: invalid entry compressed size (expected 113177 but got 113312 bytes)

The following code is what I'm trying to run to simply copy a .png image from dice.zip and adding it to diceUp.zip.

public class Test {
public static void main(String[] args) throws IOException{
    ZipFile zipFile = new ZipFile("dice.zip");
    final ZipOutputStream zos = new ZipOutputStream(new FileOutputStream("diceUp.zip"));
    for(Enumeration<? extends ZipEntry> e = zipFile.entries(); e.hasMoreElements(); ) {
        ZipEntry entryIn = (ZipEntry) e.nextElement();
            if(entryIn.getName().contains(".png")){
                System.out.println(entryIn.getName());
                zos.putNextEntry(entryIn);
                InputStream is = zipFile.getInputStream(entryIn);
                byte [] buf = new byte[1024];
                int len;
                while((len = (is.read(buf))) > 0) {            
                    zos.write(buf, 0, (len < buf.length) ? len : buf.length);
                }
        }
        zos.closeEntry();
    }
    zos.close();
}

Solution

  • Just create new ZipEntry object with the name of entryIn object and put this new object in zos.putNextEntry .
    Look at this qustion!
    And this is my code:

        public static void main(String[] args) throws IOException {
        ZipFile zipFile = new ZipFile("/home/*********/resources/dice.zip");
    //        ZipFile zipFile = new ZipFile();
        final ZipOutputStream zos = new ZipOutputStream(new FileOutputStream("diceUp.zip"));
        for (Enumeration<? extends ZipEntry> e = zipFile.entries(); e.hasMoreElements(); ) {
            ZipEntry entryIn = e.nextElement();
            if (entryIn.getName().contains(".png")) {
                System.out.println(entryIn.getName());
                ZipEntry zipEntry = new ZipEntry(entryIn.getName());
                zos.putNextEntry(zipEntry);
                InputStream is = zipFile.getInputStream(entryIn);
                byte[] buf = new byte[1024];
                int len;
                while ((len = (is.read(buf))) > 0) {
    //                    zos.write(buf, 0, (len < buf.length) ? len : buf.length);
                    zos.write(buf);
                }
            }
            zos.closeEntry();
        }
        zos.close();
    }