1

我正在尝试在 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 存档?

任何帮助表示赞赏,在此先感谢。

4

3 回答 3

1

不确定这是否会帮助您,因为您使用的是不同的库,但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文件,然后在加密后,您可以用新条目替换上一个条目。

于 2015-04-29T11:45:54.983 回答
0

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

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

于 2015-04-29T10:53:05.610 回答
0

答对了!

我可以那样做

ZipParameters parameters = new ZipParameters();
parameters.setIncludeRootFolder(true);
zipFile.removeFile(fh);
zipFile.addFolder(new File(tempdir.toFile(), "META-INF"), parameters);
于 2015-04-29T11:15:53.230 回答