欢迎访问个人博客 德鲁大叔撸代码
说明:注意引入的依赖!!!! 否则一直报错 很不容易找到的错误!!!
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
一、压缩文件
压缩前效果:
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200320142147659.png)
压缩后效果
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200320142223753.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L20wXzQzNTg0MDE2,size_16,color_FFFFFF,t_70)
解压缩输入密码
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200320142246987.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L20wXzQzNTg0MDE2,size_16,color_FFFFFF,t_70)
@Test
public void createZipFile(){
String password = "123456"; // 设置压缩密码 解压的时候需要输入该密码进行解压
String filePath = "D:\\app\\SFiles\\toprs\\createfile\\test\\";
String sourceFileName = "20200319_6666000001060017_div.csv";
File sourceFile = new File(filePath+sourceFileName);
String zipFileName = sourceFileName.replace(".csv",".zip");
log.info("开始压缩文件,压缩后的文件名为:{}",zipFileName);
ZipFile zipFile;
try {
zipFile = new ZipFile(filePath+zipFileName);
File deleteFile = zipFile.getFile();
if (deleteFile.exists()) {
deleteFile.delete();
}
ZipParameters parameters = new ZipParameters();
parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
parameters.setEncryptFiles(true);
parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);
parameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);
parameters.setPassword(password);
zipFile.addFile(sourceFile, parameters);
log.info("文件{}压缩成功",sourceFileName);
}catch (Exception e){
log.info("压缩文件:{}失败",sourceFileName);
}
}
二、解压文件
public void unzip(String zipFileName, String unPath, String password) throws ZipException {
try {
ZipFile zipFile = new ZipFile(zipFileName);
zipFile.setFileNameCharset("GBK");
if (!zipFile.isValidZipFile()) {
throw new ZipException("压缩文件不合法,可能被损坏");
}
File destDir = new File(unPath);
if (destDir.isDirectory() && !destDir.exists()) {
destDir.mkdir();
}
if (zipFile.isEncrypted()) {
zipFile.setPassword(password.toCharArray());
}
zipFile.extractAll(unPath);
} catch (Exception e) {
throw new BizException("解压zip文件失败");
}
}