3

生成压缩包的多种方式——Java【下】

 1 year ago
source link: https://blog.51cto.com/u_15426660/5915904
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

生成压缩包的多种方式——Java【下】

精选 原创

上篇推荐的压缩方法,用起来还可以吧!但是文章最后提了一句:如何给压缩包设置压缩密码?别慌!缺一个压缩包设置压缩密码而已,立马补上~其实上篇文章仔细看的宝,应该有在【​ ​hutool压缩文档​​】最后面看到压缩包设置压缩密码方法吧!

生成压缩包的多种方式——Java【下】_压缩文件

Hutool或JDK的Zip工具并不支持添加密码,可以考虑使用Zip4j完成。所以什么是Zip4j?点击打开​ ​Zip4j原文链接​​​,感兴趣的宝就自己去看看吧!接着讲项目中如何使用:

<!-- https://mvnrepository.com/artifact/net.lingala.zip4j/zip4j -->
<dependency>
<groupId>net.lingala.zip4j</groupId>
<artifactId>zip4j</artifactId>
<version>2.11.2</version>
</dependency>

Java项目使用当然是添加Maven依赖,简单点~

import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;
import java.io.*;
import java.util.ArrayList;

public class ZipTest {

public static Boolean zipFile(){
try {
//创建压缩文件
ZipFile zipFile = new ZipFile("E:/test.zip");
ArrayList<File> files = new ArrayList<>();
files.add(new File("E:/txt1.txt"));

//设置压缩文件参数
ZipParameters zipParameters = new ZipParameters();
//设置压缩方法
zipParameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);

//设置压缩级别
//DEFLATE_LEVEL_FASTEST - Lowest compression level but higher speed of compression
//DEFLATE_LEVEL_FAST - Low compression level but higher speed of compression
//DEFLATE_LEVEL_NORMAL - Optimal balance between compression level/speed
//DEFLATE_LEVEL_MAXIMUM - High compression level with a compromise of speed
//DEFLATE_LEVEL_ULTRA - Highest compression level but low speed
zipParameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);

//设置压缩文件加密
zipParameters.setEncryptFiles(true);

//设置加密方法
zipParameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);

//设置aes加密强度
zipParameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);

//设置密码
zipParameters.setPassword("123");

//添加文件到压缩文件
zipFile.addFiles(files, zipParameters);

}catch (Exception e) {
e.printStackTrace();
}
return true;
}

public static void main(String[] args) {
zipFile();
}
}

参照文档改改,就可以直接用了,好像是太简单了!不过,这样写完,功能是实现了,但是文件多起来,压缩速度不太乐观。要命!我还是想换一下,用前端生成压缩包试试。

  • 收藏
  • 2评论
  • 分享
  • 举报

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK