Error java.util.zip.ZipException: invalid entry si

2019-07-12 02:05发布

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条回答
萌系小妹纸
2楼-- · 2019-07-12 02:27

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();
}
查看更多
登录 后发表回答