一、pom依赖

        <groupId>org.apache.commons</groupId><artifactId>commons-compress</artifactId><version>1.9</version></dependency><dependency><groupId>org.tukaani</groupId><artifactId>xz</artifactId><version>1.5</version></dependency><!-- rar解压依赖 --><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>

二、工具类实现


import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.github.yulichang.common.support.func.S;
import com.onemap.business.web.resultsCheck.service.impl.ResultPackageReportServiceImpl;
import com.onemap.common.utils.StringUtils;
import net.sf.sevenzipjbinding.*;
import net.sf.sevenzipjbinding.impl.RandomAccessFileInStream;
import net.sf.sevenzipjbinding.simple.ISimpleInArchive;
import net.sf.sevenzipjbinding.simple.ISimpleInArchiveItem;
import org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry;
import org.apache.commons.compress.archivers.sevenz.SevenZFile;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.LongFunction;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;/*** 文件解压缩工具类*/
public class UnPagFileUtil {private static final Logger log = LoggerFactory.getLogger(UnFileUtil.class);/*** rar解压缩* @param rarFile    rar文件的全路径* @param outPath  解压路径* @return  压缩包中所有的文件*/public static void unRarZip7Z(String rarFile, String outPath) throws Exception {if (rarFile.toLowerCase().endsWith(".zip")) {unZip(rarFile, outPath, false);} else if (rarFile.toLowerCase().endsWith(".rar")) {unRar(rarFile, outPath, "");} else if (rarFile.toLowerCase().endsWith(".7z")) {un7z(rarFile, outPath);}}/*** rar解压缩* @param rarFile    rar文件的全路径* @param outPath  解压路径* @return  压缩包中所有的文件*/private static String unRar(String rarFile, String outPath, String passWord) {RandomAccessFile randomAccessFile = null;IInArchive inArchive = null;try {// 第一个参数是需要解压的压缩包路径,第二个参数参考JdkAPI文档的RandomAccessFilerandomAccessFile = new RandomAccessFile(rarFile, "r");if (StringUtils.isNotBlank(passWord)) {inArchive = SevenZip.openInArchive(null, new RandomAccessFileInStream(randomAccessFile), passWord);} else {inArchive = 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(outPath + File.separator+ 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 "";}/*** 获取压缩包中的全部文件* @param path    文件夹路径* @childName   每一个文件的每一层的路径==D==区分层数* @return  压缩包中所有的文件*/private static Map<String, String> getFileNameList(String path, String childName) {System.out.println("path:" + path + "---childName:"+childName);Map<String, String> files = new HashMap<>();File file = new File(path); // 需要获取的文件的路径String[] fileNameLists = file.list(); // 存储文件名的String数组File[] filePathLists = file.listFiles(); // 存储文件路径的String数组for (int i = 0; i < filePathLists.length; i++) {if (filePathLists[i].isFile()) {files.put(fileNameLists[i] + "==D==" + childName, path + File.separator + filePathLists[i].getName());} else {files.putAll(getFileNameList(path + File.separator + filePathLists[i].getName(), childName + "&" + filePathLists[i].getName()));}}return files;}/*** zip解压缩* @param zipFilePath            zip文件的全路径* @param unzipFilePath            解压后文件保存路径* @param includeZipFileName    解压后文件是否包含压缩包文件名,true包含,false不包含* @return 压缩包中所有的文件*/public static Map<String, String> unZip(String zipFilePath, String unzipFilePath, boolean includeZipFileName) throws Exception{File zipFile = new File(zipFilePath);//如果包含压缩包文件名,则处理保存路径if(includeZipFileName){String fileName = zipFile.getName();if(StringUtils.isNotEmpty(fileName)){fileName = fileName.substring(0,fileName.lastIndexOf("."));}unzipFilePath = unzipFilePath + File.separator + fileName;}//判断保存路径是否存在,不存在则创建File unzipFileDir = new File(unzipFilePath);if(!unzipFileDir.exists() || !unzipFileDir.isDirectory()){unzipFileDir.mkdirs();}//开始解压ZipEntry entry = null;String entryFilePath = null, entryDirPath = "";File entryFile = null, entryDir = null;int index = 0, count = 0, bufferSize = 1024;byte[] buffer = new byte[bufferSize];BufferedInputStream bis = null;BufferedOutputStream bos = null;Charset gbk = Charset.forName("GBK");ZipFile zip = new ZipFile(zipFile, gbk);try {Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zip.entries();while (entries.hasMoreElements()) {entry = entries.nextElement();entryFilePath = unzipFilePath + File.separator + entry.getName();entryFilePath = entryFilePath.replace("/", File.separator);index = entryFilePath.lastIndexOf(File.separator);if (index != -1) {entryDirPath = entryFilePath.substring(0, index);}entryDir = new File(entryDirPath);if (!entryDir.exists() || !entryDir.isDirectory()) {entryDir.mkdirs();}entryFile = new File(entryFilePath);//判断当前文件父类路径是否存在,不存在则创建if(!entryFile.getParentFile().exists() || !entryFile.getParentFile().isDirectory()){entryFile.getParentFile().mkdirs();}//不是文件说明是文件夹创建即可,无需写入if(entryFile.isDirectory()){continue;}bos = new BufferedOutputStream(new FileOutputStream(entryFile));bis = new BufferedInputStream(zip.getInputStream(entry));while ((count = bis.read(buffer, 0, bufferSize)) != -1) {bos.write(buffer, 0, count);}}}catch (Exception e){e.printStackTrace();}finally {bos.flush();bos.close();bis.close();zip.close();}Map<String, String> resultMap = getFileNameList(unzipFilePath, "");return resultMap;}/*** zip解压缩* @param zipFilePath            zip文件的全路径* @param includeZipFileName    解压后文件是否包含压缩包文件名,true包含,false不包含* @return 压缩包中所有的文件*/public static Map<String, String> unZip(String zipFilePath, boolean includeZipFileName) throws Exception{File zipFile = new File(zipFilePath);String unzipFilePath = zipFilePath.substring(0, zipFilePath.lastIndexOf(File.separator));//如果包含压缩包文件名,则处理保存路径if(includeZipFileName){String fileName = zipFile.getName();if(StringUtils.isNotEmpty(fileName)){fileName = fileName.substring(0,fileName.lastIndexOf("."));}unzipFilePath = unzipFilePath + File.separator + fileName;}//判断保存路径是否存在,不存在则创建File unzipFileDir = new File(unzipFilePath);if(!unzipFileDir.exists() || !unzipFileDir.isDirectory()){unzipFileDir.mkdirs();}//开始解压ZipEntry entry = null;String entryFilePath = null, entryDirPath = "";File entryFile = null, entryDir = null;int index = 0, count = 0, bufferSize = 1024;byte[] buffer = new byte[bufferSize];BufferedInputStream bis = null;BufferedOutputStream bos = null;Charset gbk = Charset.forName("GBK");ZipFile zip = new ZipFile(zipFile, gbk);try {Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zip.entries();while (entries.hasMoreElements()) {entry = entries.nextElement();entryFilePath = unzipFilePath + File.separator + entry.getName();entryFilePath = entryFilePath.replace("/", File.separator);index = entryFilePath.lastIndexOf(File.separator);if (index != -1) {entryDirPath = entryFilePath.substring(0, index);}entryDir = new File(entryDirPath);if (!entryDir.exists() || !entryDir.isDirectory()) {entryDir.mkdirs();}entryFile = new File(entryFilePath);//判断当前文件父类路径是否存在,不存在则创建if(!entryFile.getParentFile().exists() || !entryFile.getParentFile().isDirectory()){entryFile.getParentFile().mkdirs();}//不是文件说明是文件夹创建即可,无需写入if(entryFile.isDirectory()){continue;}bos = new BufferedOutputStream(new FileOutputStream(entryFile));bis = new BufferedInputStream(zip.getInputStream(entry));while ((count = bis.read(buffer, 0, bufferSize)) != -1) {bos.write(buffer, 0, count);}bos.flush();bos.close();bis.close();}}catch (Exception e){e.printStackTrace();}finally {zip.close();}Map<String, String> resultMap = getFileNameList(unzipFilePath, "");return resultMap;}/*** 7z解压缩* @param z7zFilePath    7z文件的全路径* @param outPath  解压路径* @return  压缩包中所有的文件*/public static Map<String, String> un7z(String z7zFilePath, String outPath){SevenZFile zIn = null;try {File file = new File(z7zFilePath);zIn = new SevenZFile(file);SevenZArchiveEntry entry = null;File newFile = null;while ((entry = zIn.getNextEntry()) != null){//不是文件夹就进行解压if(!entry.isDirectory()){newFile = new File(outPath, entry.getName());if(!newFile.exists()){new File(newFile.getParent()).mkdirs();   //创建此文件的上层目录}OutputStream out = new FileOutputStream(newFile);BufferedOutputStream bos = new BufferedOutputStream(out);int len = -1;byte[] buf = new byte[(int)entry.getSize()];while ((len = zIn.read(buf)) != -1){bos.write(buf, 0, len);}bos.flush();bos.close();out.close();}}} catch (Exception e) {e.printStackTrace();}finally {try {if (zIn != null) {zIn.close();}} catch (IOException e) {e.printStackTrace();}}Map<String, String> resultMap = getFileNameList(outPath, "");return resultMap;}public static void main(String[] args) {try {String inputFile = "E:\\新建文件夹 (2)\\压缩测试.zip";String inputFile2 = "E:\\新建文件夹 (2)\\红光村批复.rar";String inputFile3 = "E:\\新建文件夹 (2)\\压缩测试.7z";String destDirPath = "E:\\新建文件夹\\zip";String destDirPath2 = "E:\\新建文件夹\\rar";String destDirPath3 = "E:\\新建文件夹\\7z";String suffix = inputFile.substring(inputFile.lastIndexOf("."));//File zipFile = new File("E:\\新建文件夹 (2)\\压缩测试.7z");//un7z(inputFile3, destDirPath3);//unZip(inputFile, destDirPath, false);unRar(inputFile2, destDirPath2, "");} catch (Exception e) {e.printStackTrace();}}}

JAVA常见压缩包解压工具类(支持:zip、7z和rar)相关推荐

  1. java的tgz解压工具类

    前言 之前在代码上一直使用的是对zip的解压,最近对接方居然使用了tgz的压缩包,在网上找了一个工具类,在项目测试,使用. 直接贴上tgz解压代码. public class PackDecompre ...

  2. java gzip 压缩解压工具类

    因为觉得简单,本想抱着百度直接拿过来用的心态,结果发现网上的代码都转载自同一份,且埋了一个坑,你不仔细去梳理,很难发现. mark下需要注意的两点: 1. 编码/解码,压缩/解压缩是成对出现的 编码: ...

  3. 【文件压缩解压工具类-含密码】

    文件压缩解压工具类-含密码 一.zip4j简介 二.zip4j工具类使用步骤 1.添加maven依赖 2.工具类代码 3.调用测试 三.结语 一.zip4j简介 zip4j功能比较强大,支持加密.解密 ...

  4. java常用地图坐标系转换工具类,支持谷歌,腾讯,百度等主流的地理坐标转换

    package com.shen.springboot.redis.util;import java.util.ArrayList; import java.util.HashMap; import ...

  5. 7z001怎么解压在安卓手机上面_安卓zip文件压缩RAR解压手机下载-安卓zip文件压缩RAR解压v1.0最新版下载...

    安卓zip文件压缩RAR解压是一款非常好用的手机压缩解压缩神器,在安卓zip文件压缩RAR解压上我们可以看到很多的实用的功能,软件可以帮助我们更好的处理我们手机中的文件,感兴趣的朋友赶紧下载安卓zip ...

  6. cordova 安卓文件多选_安卓zip文件压缩RAR解压软件下载-安卓zip文件压缩RAR解压下载v3.0.4安卓版...

    安卓zip文件压缩RAR解压是一款非常好用的手机压缩解压缩神器,在安卓zip文件压缩RAR解压上我们可以看到很多的实用的功能,软件可以帮助我们更好的处理我们手机中的文件,感兴趣的朋友赶紧下载安卓zip ...

  7. Java zip解压工具类

    分享一个自己用的zip工具类 public class ZipUtils {public static void unZip(File srcFile, String destDirPath) thr ...

  8. Java_压缩与解压工具类

    转载请注明出处:http://blog.csdn.net/y22222ly/article/details/52201675 zip压缩,解压 zip压缩与解压主要依靠java api的两个类: Zi ...

  9. java常见的时间处理工具类

    import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date;public class Get ...

最新文章

  1. 在自己的网站添加关注新浪关注按钮
  2. mybatis-plus AutoGenerator
  3. 解决vs2005打开vs2008应用程序方法
  4. 挖掘机燃料_2020广东挖掘机工程机械出租公司合作共赢
  5. DS5020配置集群存储
  6. java run里面定义变量_Java程序员50多道最热门的多线程和并发面试题(答案解析)...
  7. 视觉(5)A Fast Area-Based Stereo Matching Algorithm
  8. 被马云逼上绝路,睡了12年宾馆!中国最狠会计,拿下4600亿
  9. 林斌首曝红米骁龙855旗舰新机:3200万像素弹出式前置摄像头
  10. Centos升级安装.Net core 1.1
  11. (转) 分布式-微服务-集群的区别
  12. OpenShift——openshift 3.11 集群安装(亲测版,你懂的)
  13. svn的安装出现报错问题解决办法
  14. c语言求范围内最大素数,for语句计算输出10000以内最大素数怎么搞最简单??各位大神们...
  15. vtk 提取等值面并显示
  16. zzulioj 1183: 平面点排序(一)(结构体专题)
  17. 【知识兔】Excel教程:批量合并相同内容单元格神技
  18. 基于ZigBee 的多点温度采集系统设计与实现
  19. GPS从入门到放弃(八) --- GPS卫星速度解算
  20. 成都学编程哪个学校好

热门文章

  1. 【Unity3D】无法正确获取RectTransform的属性值导致计算出错
  2. ionic 前端 - 汉字转拼音
  3. 看视频、走个路就能赚钱?警惕个人信息泄露
  4. Google Earth Engine(GEE)——几何图形ee.Geometry
  5. 『创意欣赏』60款惊艳的 iOS App 图标设计《第四季》
  6. 8年经验分享:想要成为一名合格的软件测试工程师,你得会些啥?
  7. 小型故障FCPX转场:YCImaging Transitions for Mac
  8. 如何使用掘金进行量化策略效析
  9. 武汉理工计算机保研去向,武汉理工大学2020届保研率14.8%(感谢网友@909578090)...
  10. 7代cpu能装虚拟xp系统吗_小米手机最新系统MIUI 11 推荐