2

我正在尝试修改现有的 .zip 文件,然后创建修改后的副本。

我可以轻松地对除 zip 文件中的 .png 文件之外的所有文件执行此操作,这会导致错误

java.util.zip.ZipException:无效的条目压缩大小(预期为 113177 但得到 113312 字节)

下面的代码是我试图运行的简单地从 dice.zip 复制 .​​png 图像并将其添加到 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();
}
4

1 回答 1

2

只需使用entryIn对象的名称创建新的ZipEntry对象并将这个新对象放入zos.putNextEntry中。 看看这个问题! 这是我的代码:

    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();
}
于 2016-06-05T18:46:33.657 回答