在一些日常业务中,会遇到一些琐碎文件需要统一打包到一个压缩包中上传,业务方在后台接收到压缩包后自行解压,然后解析相应文件。而且可能涉及安全保密,因此会在压缩时带上密码,要求后台业务可以指定密码进行解压。

应用环境说明:jdk1.8,maven3.x,需要基于java语言实现对zip、rar、7z等常见压缩包的解压工作。

首先关于zip和rar、7z等压缩工具和压缩算法就不在此赘述,下面通过一个数据对比,使用上述三种不同的压缩算法,采用默认的压缩方式,看到压缩的文件大小如下:

转换成图表看得更直观,如下图:

从以上图表可以看到,7z的压缩率是最高,而zip压缩率比较低,rar比zip稍微好点。单纯从压缩率看,7z>rar4>rar5>zip。

下面具体说明在java中如何进行相应解压:

1、pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.yelang</groupId><artifactId>7zdemo</artifactId><version>0.0.1-SNAPSHOT</version><dependencies><dependency><groupId>net.lingala.zip4j</groupId><artifactId>zip4j</artifactId><version>2.9.0</version></dependency><dependency><groupId>net.sf.sevenzipjbinding</groupId><artifactId>sevenzipjbinding</artifactId><version>16.02-2.01</version></dependency><dependency><groupId>net.sf.sevenzipjbinding</groupId><artifactId>sevenzipjbinding-all-platforms</artifactId><version>16.02-2.01</version></dependency><dependency><groupId>org.tukaani</groupId><artifactId>xz</artifactId><version>1.9</version></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-compress</artifactId><version>1.21</version></dependency><!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api --><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-api</artifactId><version>1.7.30</version></dependency><!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 --><dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId><version>3.12.0</version></dependency><!-- https://mvnrepository.com/artifact/fr.opensagres.xdocreport/xdocreport --><dependency><groupId>fr.opensagres.xdocreport</groupId><artifactId>xdocreport</artifactId><version>1.0.6</version></dependency></dependencies>
</project>

主要依赖的jar包有:zip4j、sevenzipjbinding等。

2、zip解压

 @SuppressWarnings("resource")
private static String unZip(String rootPath, String sourceRarPath, String destDirPath, String passWord) {ZipFile zipFile = null;String result = "";try {//String filePath = sourceRarPath;String filePath = rootPath + sourceRarPath;if (StringUtils.isNotBlank(passWord)) {zipFile = new ZipFile(filePath, passWord.toCharArray());} else {zipFile = new ZipFile(filePath);}zipFile.setCharset(Charset.forName("GBK"));zipFile.extractAll(rootPath + destDirPath);} catch (Exception e) {log.error("unZip error", e);return e.getMessage();}return result;}

3、rar解压

private static String unRar(String rootPath, String sourceRarPath, String destDirPath, String passWord) {String rarDir = rootPath + sourceRarPath;String outDir = rootPath + destDirPath + File.separator;RandomAccessFile randomAccessFile = null;IInArchive inArchive = null;try {// 第一个参数是需要解压的压缩包路径,第二个参数参考JdkAPI文档的RandomAccessFilerandomAccessFile = new RandomAccessFile(rarDir, "r");if (StringUtils.isNotBlank(passWord))inArchive = SevenZip.openInArchive(null, new RandomAccessFileInStream(randomAccessFile), passWord);elseinArchive = SevenZip.openInArchive(null, new RandomAccessFileInStream(randomAccessFile));ISimpleInArchive simpleInArchive = inArchive.getSimpleInterface();for (final ISimpleInArchiveItem item : simpleInArchive.getArchiveItems()) {final int[] hash = new int[]{0};if (!item.isFolder()) {ExtractOperationResult result;final long[] sizeArray = new long[1];File outFile = new File(outDir + item.getPath());File parent = outFile.getParentFile();if ((!parent.exists()) && (!parent.mkdirs())) {continue;}if (StringUtils.isNotBlank(passWord)) {result = item.extractSlow(data -> {try {IOUtils.write(data, new FileOutputStream(outFile, true));} catch (Exception e) {e.printStackTrace();}hash[0] ^= Arrays.hashCode(data); // Consume datasizeArray[0] += data.length;return data.length; // Return amount of consumed}, passWord);} else {result = item.extractSlow(data -> {try {IOUtils.write(data, new FileOutputStream(outFile, true));} catch (Exception e) {e.printStackTrace();}hash[0] ^= Arrays.hashCode(data); // Consume datasizeArray[0] += data.length;return data.length; // Return amount of consumed});}if (result == ExtractOperationResult.OK) {log.error("解压rar成功...." + String.format("%9X | %10s | %s", hash[0], sizeArray[0], item.getPath()));} else if (StringUtils.isNotBlank(passWord)) {log.error("解压rar成功:密码错误或者其他错误...." + result);return "password";} else {return "rar error";}}}} catch (Exception e) {log.error("unRar error", e);return e.getMessage();} finally {try {inArchive.close();randomAccessFile.close();} catch (Exception e) {e.printStackTrace();}}return "";}

4、7z解压

 private static String un7z(String rootPath, String sourceRarPath, String destDirPath, String passWord) {try {File srcFile = new File(rootPath + sourceRarPath);//获取当前压缩文件// 判断源文件是否存在if (!srcFile.exists()) {throw new Exception(srcFile.getPath() + "所指文件不存在");}//开始解压SevenZFile zIn = null;if (StringUtils.isNotBlank(passWord)) {zIn = new SevenZFile(srcFile, passWord.toCharArray());}  else {zIn = new SevenZFile(srcFile);}SevenZArchiveEntry entry = null;File file = null;while ((entry = zIn.getNextEntry()) != null) {if (!entry.isDirectory()) {file = new File(rootPath + destDirPath, entry.getName());if (!file.exists()) {new File(file.getParent()).mkdirs();//创建此文件的上级目录}OutputStream out = new FileOutputStream(file);BufferedOutputStream bos = new BufferedOutputStream(out);int len = -1;byte[] buf = new byte[1024];while ((len = zIn.read(buf)) != -1) {bos.write(buf, 0, len);}// 关流顺序,先打开的后关闭bos.close();out.close();}}} catch (Exception e) {log.error("un7z is error", e);return e.getMessage();}return "";}

5、解压统一入口封装

public static Map<String,Object> unFile(String rootPath, String sourcePath, String destDirPath, String passWord) {Map<String,Object> resultMap = new HashMap<String, Object>();String result = "";if (sourcePath.toLowerCase().endsWith(".zip")) {//Wrong password!result = unZip(rootPath, sourcePath, destDirPath, passWord);} else if (sourcePath.toLowerCase().endsWith(".rar")) {//java.security.InvalidAlgorithmParameterException: password should be specifiedresult = unRar(rootPath, sourcePath, destDirPath, passWord);System.out.println(result);} else if (sourcePath.toLowerCase().endsWith(".7z")) {//PasswordRequiredException: Cannot read encrypted content from G:\ziptest\11111111.7z without a passwordresult = un7z(rootPath, sourcePath, destDirPath, passWord);}resultMap.put("resultMsg", 1);if (StringUtils.isNotBlank(result)) {if (result.contains("password")) resultMap.put("resultMsg", 2);if (!result.contains("password")) resultMap.put("resultMsg", 3);}resultMap.put("files", null);//System.out.println(result + "==============");return resultMap;}

6、测试代码

Long start = System.currentTimeMillis();
unFile("D:/rarfetch0628/","apache-tomcat-8.5.69.zip","apache-tomcat-zip","222");
long end = System.currentTimeMillis();
System.out.println("zip解压耗时==" + (end - start) + "毫秒");
System.out.println("============================================================");Long rar4start = System.currentTimeMillis();
unFile("D:/rarfetch0628/","apache-tomcat-8.5.69-4.rar","apache-tomcat-rar4","222");
long rar4end = System.currentTimeMillis();
System.out.println("rar4解压耗时==" + (rar4end - rar4start)+ "毫秒");
System.out.println("============================================================");Long rar5start = System.currentTimeMillis();
unFile("D:/rarfetch0628/","apache-tomcat-8.5.69-5.rar","apache-tomcat-rar5","222");
long rar5end = System.currentTimeMillis();
System.out.println("rar5解压耗时==" + (rar5end - rar5start)+ "毫秒");
System.out.println("============================================================");Long zstart = System.currentTimeMillis();
unFile("D:/rarfetch0628/","apache-tomcat-8.5.69.7z","apache-tomcat-7z","222");
long zend = System.currentTimeMillis();
System.out.println("7z解压耗时==" + (zend - zstart)+ "毫秒");
System.out.println("============================================================");

在控制台中可以看到以下结果:

总结:本文采用java语言实现了对zip和rar、7z文件的解压统一算法。并对比了相应的解压速度,支持传入密码进行在线解压。本文参考了:https://blog.csdn.net/luanwuqingyang/article/details/121114113,不过博主的文章代码直接运行有问题,这里进行了调整,主要优化的点如下:

1、pom.xml 遗漏了slf4j、commons-lang3、xdocreport等依赖

2、zip路径优化

3、去掉一些无用信息

4、优化异常信息

java对zip、rar、7z文件带密码解压实例相关推荐

  1. android zip 开源 加密,Android带密码解压----Zip4J开源项目使用

    最近工作过程中,需要在Android项目中对一个带密码的压缩文件进行解压 ,之前就知道Java API中提供了 java.util.zip.*;包来支持Java对于压缩文件的相关压缩,解压缩操作.所以 ...

  2. 根据链接下载zip文件并用密码解压

    根据链接下载zip文件并用密码解压(亲测可用) 导入所需要的pom(注意版本) 导入所需要的pom(注意版本) 导入所需要的pom(注意版本) <dependency><groupI ...

  3. 7z文件压缩、解压 (7zTool.exe)

    工具下载 压缩为7z: 调用zip()函数 7z解压缩: 调用unzip()函数 using System; using System.Collections.Generic; using Syste ...

  4. Android解压zip rar 7z文件

    添加依赖 implementation 'org.apache.commons:commons-compress:1.23.0' implementation 'com.github.junrar:j ...

  5. linux带密码解压密码,linux 下文件加密压缩和解压的方法

    方法一:用tar命令 对文件加密压缩和解压 压缩: [html] view plain copy tar -zcf - filename |openssl des3 -salt -k password ...

  6. java实现 zip rar 7z 压缩包解压

    1.7z和rar需要引入maven依赖,zip使用java自带的 <!-- 7z解压依赖 --><dependency><groupId>org.apache.co ...

  7. 如何快速解压/打开zip/rar/7z文件包?在线解压工具推荐

    看了很多帖子,都是推荐下载解压软件进行解压,推荐一个在线版的解压服务. 用浏览器开箱即用.现在已经支持.zip.zipx.rar.tar.gz.tgz.7z.采用的是前端的技术栈,所以解压服务是发生在 ...

  8. Mac 解压rar格式文件(附解压工具包)

    Mac 解压rar格式文件* 工具包(zip格式):http://download.csdn.net/detail/u011445031/9854187 将工具包解压到你安装目录即可. 使用: 打开终 ...

  9. linux解压7z文件,linux 中解压7z文件

    linux 中解压7z文件 更新时间:2017-03-26 00:13:50 linux 解压.解压7z文件方法 安装7z源[root@VM_18_10_centos ~]# sudo yum ins ...

  10. java上传rar文件_java实现上传zip/rar压缩文件,自动解压

    在pom中添加解压jar依赖 4.0.0 org.springframework.boot spring-boot-starter-parent 2.1.2.RELEASE com.hf uncomp ...

最新文章

  1. 机器学习实践中的10个小秘诀!
  2. 登录界面的滑动_电脑同时登录两个微信,原来这么简单?3步搞定!
  3. OA实施成功率提升,流程梳理是关键
  4. Alcatraz插件安装问题
  5. java的内存模型--jmm
  6. python asyncio 异步编程---协程
  7. 在java中对null的理解
  8. delphi的 PosEx 函数功能介绍
  9. C#正则表达式 — 正则表达式类
  10. G.8032协议 ERPS
  11. c语言飞机大战游戏素材,jQuery飞机大战游戏
  12. Python编程之二维码生成
  13. 计算机毕业设计论文——国内外文献查找网站
  14. kubeadm搭建k8s集群
  15. 少儿编程启蒙课程9:善用变量 拥抱变化
  16. 25篇最新CV领域综述性论文速递!涵盖15个方向:目标检测/图像处理/姿态估计/医学影像/人脸识别等方向...
  17. 回收站文件清理了怎么恢复
  18. “江湖笑”-献给怀有梦想的北漂一族
  19. 内部振荡器、无源晶振、有源晶振有什么区别?
  20. read方法阻塞的解决

热门文章

  1. 金蝶服务器换了无线网怎么办,搬家后wifi怎么重新设置?
  2. 人体动作捕捉与SMPL模型 (mocap and SMPL model)
  3. Chrome安装HttpWatch
  4. 一般线性模型(general linear model,GLM)
  5. Nginx模块开发之http handler实现流量统计(入门篇)
  6. Interpretable Machine Learning中GLM,GAM等
  7. 93年券商未转正员工猝死:一个金融人要牺牲多少健康,才能保住饭碗?
  8. 离线安装vscode
  9. 从周易六十四卦看软件架构真好懂!女朋友这下不用担心我的学习了~【程序员编程】
  10. 好佳居软装十大品牌 软装类型对应着主人