工作遇到,记录下
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;
import org.springframework.web.bind.annotation.PostMapping;
import java.io.File;
/**
* 文件夹压缩加密
*/
public class ZipEncrypt {
/**
* zip加密
* @param filePath 文件夹路径
* @param savePath 压缩后的路径
* @param password 密码
*/
public static ZipFile zipEncrypt(String filePath, String savePath, String password) throws ZipException {
File file = new File(filePath);
ZipFile zipFile = new ZipFile(savePath);
// 设置zip包的一些参数集合
ZipParameters parameters = new ZipParameters();
// 是否设置密码(此处设置为:是)
parameters.setEncryptFiles(true);
// 压缩方式(默认值)
parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
// 普通级别
parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
// 加密级别
parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_STANDARD);
// 压缩包密码
parameters.setPassword(password);
if (file.isDirectory()) {
zipFile.createZipFileFromFolder(file, parameters, false, -1L);
} else {
zipFile.createZipFile(file, parameters);
}
return zipFile;
}
}