在 Java 中替换 Zip 存档中的特定文件而不提取整个存档

Replace specific file inside Zip archive without extracting the whole archive in Java

我正在尝试获取 Zip 存档中的特定文件,将其解压缩、加密,然后将其放回存档中替换原始文件。

这是我到目前为止尝试过的方法..

public static boolean encryptXML(File ZipArchive, String key) throws ZipException, IOException, Exception {
    ZipFile zipFile = new ZipFile(ZipArchive);
    List<FileHeader> fileHeaderList = zipFile.getFileHeaders();
    for (FileHeader fh : fileHeaderList)
    {
        if (fh.getFileName().equals("META-INF/file.xml"))
        {
            Path tempdir = Files.createTempDirectory("Temp");
            zipFile.extractFile(fh, tempdir.toString());
            File XMLFile = new File(tempdir.toFile(), fh.getFileName());

            // Encrypting XMLFile, Ignore this part

            // Here, Replace the original XMLFile inside ZipArchive with the encrypted one <<<<<<<<

            return true;
        }
    }
    return false;
}

我停留在代码的替换部分,无论如何我可以做到这一点而不必提取整个 Zip 存档?

感谢任何帮助,提前致谢。

您可以按照 Oracle documentation 至 read/write 中的说明在 zip 文件中使用 ZipFilesystem(从 Java 7 开始),就像它是自己的文件系统一样。

但是,在我的机器上,这无论如何都会在引擎盖下解压和重新打包 zip 文件(用 7 和 8 测试)。我不确定是否有办法像您描述的那样可靠地更改 zip 文件。

宾果!

我可以那样做

ZipParameters parameters = new ZipParameters();
parameters.setIncludeRootFolder(true);
zipFile.removeFile(fh);
zipFile.addFolder(new File(tempdir.toFile(), "META-INF"), parameters);

不确定这是否对您有帮助,因为您使用的是不同的库,但 ZT Zip 中的解决方案如下。

ZipUtil.unpackEntry(new File("/tmp/demo.zip"), "foo.txt", new File("foo.txt"));
// encrypt the foo.txt
ZipUtil.replaceEntry(new File("/tmp/demo.zip"), "foo.txt", new File("foo.txt"));

这将解压缩 foo.txt 文件,然后在加密后,您可以用新的条目替换以前的条目。