<dependency>
<groupId>net.lingala.zip4j</groupId>
<artifactId>zip4j</artifactId>
<version>2.6.4</version>
</dependency>
public static void zip(File currentDir, String toFilePath, String password) throws Exception {
// 生成的压缩文件
ZipFile zipFile = new ZipFile(toPath);
ZipParameters parameters = new ZipParameters();
// 压缩方式
parameters.setCompressionMethod(CompressionMethod.DEFLATE);
// 压缩级别
parameters.setCompressionLevel(CompressionLevel.NORMAL);
// 是否设置加密文件
parameters.setEncryptFiles(true);
// 设置加密算法
parameters.setEncryptionMethod(EncryptionMethod.AES);
// 设置AES加密密钥的密钥强度
parameters.setAesKeyStrength(AesKeyStrength.KEY_STRENGTH_256);
// 设置密码
if(!Strings.isNullOrEmpty(password)) {
zipFile.setPassword(password.toCharArray());
}
// 要打包的文件夹
File[] fs = currentDir.listFiles();
// 遍历test文件夹下所有的文件、文件夹
for (File f : fList) {
if (f.isDirectory()) {
zipFile.addFolder(f, parameters);
} else {
zipFile.addFile(f, parameters);
}
}
}
public static void unzip(String zipFilePath, String toPath, String password) throws Exception {
// 生成的压缩文件
ZipFile zipFile = new ZipFile(zipFilePath);
// 设置密码
if(!Strings.isNullOrEmpty(password)) {
zipFile.setPassword(password.toCharArray());
}
// 解压缩所有文件以及文件夹
zipFile.extractAll(toPath);
}