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

天涯浪子 提交于 2019-12-11 00:57:48

问题


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();
}

回答1:


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();
}


来源:https://stackoverflow.com/questions/37645153/error-java-util-zip-zipexception-invalid-entry-size-while-copying-image-png

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!