我可以创建一个 zip 文件,我的要求是通过密码保护它。为此,我使用的是 zip4j 库。请单击更多链接以供参考。[https://github.com/srikanth-lingala/zip4j]
下面是代码。
public static void packZip(File output, List<File> sources) throws IOException {
System.out.println("Packaging to " + output.getName());
ZipOutputStream zipOut = initializeZipOutputStream(output, "password".toCharArray());
for (File source : sources) {
if (source.isDirectory()) {
zipDir(zipOut, "", source);
} else {
zipFile(zipOut, "", source);
}
}
zipOut.flush();
zipOut.close();
System.out.println("Done");
}
private static void zipFile(ZipOutputStream zos, String path, File file) throws IOException {
if (!file.canRead()) {
return;
}
ZipParameters zipParameters = new ZipParameters();
zipParameters.setAesKeyStrength(AesKeyStrength.KEY_STRENGTH_256);
zipParameters.setCompressionLevel(CompressionLevel.NORMAL);
zipParameters.setCompressionMethod(CompressionMethod.DEFLATE);
zipParameters.setFileNameInZip(buildPath(path,file.getName()));
zos.putNextEntry(zipParameters);
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[4092];
int byteCount = 0;
while ((byteCount = fis.read(buffer)) != -1) {
zos.write(buffer, 0, byteCount);
}
ZipFile zipFile = new ZipFile(file, "password".toCharArray());
zipFile.addFile(file, zipParameters);
//zipFile.createSplitZipFileFromFolder(file, zipParameters, true, 10485760);
fis.close();
zos.closeEntry();
}
private static ZipOutputStream initializeZipOutputStream(File outputZipFile, char[] password)
throws IOException {
FileOutputStream fos = new FileOutputStream(outputZipFile);
return new ZipOutputStream(fos, password);
}
private static void zipDir(ZipOutputStream zos, String path, File dir) throws IOException {
if (!dir.canRead()) {
return;
}
File[] files = dir.listFiles();
path = buildPath(path, dir.getName());
for (File source : files) {
if (source.isDirectory()) {
zipDir(zos, path, source);
} else {
zipFile(zos, path, source);
}
}
}
当我使用 ZipFile 类进行密码保护时,我无法提取 zip 文件,在提取过程中它从 .zip 更改为 String 格式。如果我使用 ZipOutputStream 类进行密码保护,则在提取过程中文件格式没有变化,但它没有按预期询问密码。任何帮助表示赞赏,在此先感谢。