向压缩包内追加文件失败

public static void main(String[] args) throws Exception {
        // read war.zip and write to append.zip
        ZipFile war = new ZipFile("war.zip");
        ZipOutputStream append = new ZipOutputStream(new FileOutputStream("append.zip"));

        // first, copy contents from existing war
        Enumeration<? extends ZipEntry> entries = war.entries();
        while (entries.hasMoreElements()) {
            ZipEntry e = entries.nextElement();
            System.out.println("copy: " + e.getName());
            append.putNextEntry(e);
            if (!e.isDirectory()) {
                copy(war.getInputStream(e), append);
            }
            append.closeEntry();
        }

        // now append some extra content
        ZipEntry e = new ZipEntry("answer.txt");
        System.out.println("append: " + e.getName());
        append.putNextEntry(e);
        append.write("42\n".getBytes());
        append.closeEntry();

        // close
        war.close();
        append.close();
    }

上述代码只贴了部分,参考地址:https://cloud.tencent.com/developer/ask/44436

运行之后发现

ZipFile war = new ZipFile("war.zip");

这行代码报错java.util.zip.ZipException: error in opening zip file  ;原因压缩包并不是真正的zip,之后用360压缩重新生成zip;

重新运行


排查发现压缩软件生成的压缩包与代码生成压缩包有差异,文件复制失败

解决方法:利用代码生成压缩包,再追加,如果无法保证压缩包那么建议先解压在重新打包

猜你喜欢

转载自blog.csdn.net/rumengqiang/article/details/80996660