我正在尝试在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存档?
提前感谢任何帮助。
答案 0 :(得分: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
文件,然后在加密后,您可以用新文件替换上一个条目。
答案 1 :(得分:0)
您可以使用Oracle documentation中所述的ZipFilesystem(从Java 7开始)在zip文件中读/写,就好像它是自己的文件系统一样。
但是,在我的机器上,无论如何都要解压缩并重新打包引擎盖下的zip文件(使用7和8进行测试)。我不确定是否有办法可靠地更改您描述的zip文件。
答案 2 :(得分:0)
宾果!
我能够这样做
ZipParameters parameters = new ZipParameters();
parameters.setIncludeRootFolder(true);
zipFile.removeFile(fh);
zipFile.addFolder(new File(tempdir.toFile(), "META-INF"), parameters);