【问题标题】:Error java.util.zip.ZipException: invalid entry size while copying image (.png) from 1 zip file to another错误 java.util.zip.ZipException:将图像 (.png) 从 1 个 zip 文件复制到另一个文件时条目大小无效
【发布时间】:2016-10-05 08:04:48
【问题描述】:

我正在尝试修改现有的 .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();
}

【问题讨论】:

    标签: java zip png inputstream zipoutputstream


    【解决方案1】:

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

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

    【讨论】:

    • 非常感谢!我已经挣扎了好几个小时了
    猜你喜欢
    • 1970-01-01
    • 2013-02-08
    • 2023-01-26
    • 1970-01-01
    • 2011-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多