最近项目有需求对压缩文件进行解析,需要支持市面上比较流行的压缩格式,诸如zip,rar,7z;

由于压缩文件解析比较常见,特将代码整理出来,供后续参考学习;

以下是java代码:

maven依赖:

     <!-- 解压rar --><dependency><groupId>com.github.junrar</groupId><artifactId>junrar</artifactId><version>4.0.0</version></dependency><!-- 解压7z --><dependency><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>

压缩工具代码:

package xxx;import com.github.junrar.Archive;
import com.github.junrar.UnrarCallback;
import com.github.junrar.rarfile.FileHeader;
import org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry;
import org.apache.commons.compress.archivers.sevenz.SevenZFile;
import org.apache.commons.io.FileUtils;import java.io.*;
import java.util.List;
import java.util.Random;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;/*** 解压文件* 支持 zip, rar, 7z* @author pansh* @since 2021-12-7 17:28:12*/
public class UnZipUtils {public static final String PREFIX_PATH = "/opt/application/zip/";public static void main(String[] a) throws Exception {//        un7z();//        unzip();File srcFile = new File("C:\\Users\\pansh\\Desktop\\1.7z");FileInputStream fis = new FileInputStream(srcFile);copyZipFile(fis, "a.zip");//        unrar(new CustomUnrarCallback());}/*** 获取随机数* @return*/private static int getRandom () {Random r = new Random();return r.nextInt(10000);}/*** 复制压缩文件到本地* @param inputStream* @param fileName* @throws IOException*/public static File copyZipFile (InputStream inputStream, String fileName) throws IOException {StringBuffer sb = new StringBuffer();long timeMillis = System.currentTimeMillis();String randomPath = sb.append(PREFIX_PATH).append(timeMillis).append("_").append(getRandom()).toString();File zipFile = new File(randomPath + File.separator + fileName);FileUtils.copyInputStreamToFile(inputStream, zipFile);return zipFile;}/*** 删除压缩文件* @param zipFile*/public static void deleteZipFile (File zipFile) {if (zipFile.exists()) {zipFile.delete();}}/*** 解压7z文件 test*/public static void un7z () throws Exception {File srcFile = new File("C:\\Users\\pansh\\Desktop\\2.7z");// 判断源文件是否存在if (!srcFile.exists()) {throw new Exception(srcFile.getPath() + "所指文件不存在");}// 开始解压long start = System.currentTimeMillis();SevenZFile zIn = new SevenZFile(srcFile);SevenZArchiveEntry entry;while ((entry = zIn.getNextEntry()) != null) {if (!entry.isDirectory()) {String path = entry.getName();System.out.println("path=" + path);ByteArrayOutputStream out = new ByteArrayOutputStream();int len = -1;byte[] buf = new byte[1024];while ((len = zIn.read(buf)) != -1) {out.write(buf, 0, len);}InputStream inputStream = new ByteArrayInputStream(out.toByteArray());String[] pathArray = path.split("/");String fileName = pathArray[pathArray.length-1];System.out.println(fileName);File destFile = new File("C:\\Users\\pansh\\Desktop\\"+fileName);FileUtils.copyInputStreamToFile(inputStream, destFile);inputStream.close();}}zIn.close();long end = System.currentTimeMillis();System.out.println("解压"+srcFile.getName()+"耗时"+(end-start)+"毫秒");}/*** 解压rar文件 test*/public static void unrar (UnrarCallback callback) throws Exception {File file = new File("C:\\Users\\pansh\\Desktop\\2.rar");Archive archive = new Archive(file, callback);
//        Archive archive = new Archive(new FileInputStream());if(archive == null){throw new FileNotFoundException("File NOT FOUND!");}if(archive.isEncrypted()){throw new Exception("File IS ENCRYPTED!");}List<FileHeader> files =  archive.getFileHeaders();for (FileHeader fh : files) {if(fh.isEncrypted()){throw new Exception("File IS ENCRYPTED!");}if (!fh.isDirectory()) {String path = fh.getFileNameString();System.out.println("path=" + path);InputStream inputStream = archive.getInputStream(fh);String[] pathArray = path.split("\\\\");String fileName = pathArray[pathArray.length-1];System.out.println(fileName);inputStream.close();}}}/*** 解压zip文件 test*/public static void unzip () {File file = new File("C:\\Users\\pansh\\Desktop\\2.zip");ZipFile zipFile = null;ZipInputStream zin = null;FileInputStream fis = null;try {zipFile = new ZipFile(file);fis = new FileInputStream(file);zin = new ZipInputStream(fis);ZipEntry ze = null;while ((ze = zin.getNextEntry()) != null) {String path = ze.getName();System.out.println("path=" + path);if (!ze.isDirectory()) {InputStream inputStream = zipFile.getInputStream(ze);String[] pathArray = path.split("/");String fileName = pathArray[pathArray.length-1];System.out.println(fileName);inputStream.close();}}} catch (IOException e) {e.printStackTrace();} finally {try {if (zin != null) {zin.closeEntry();zin.close();}if (fis != null)fis.close();if (zipFile != null)zipFile.close();} catch (IOException e) {e.printStackTrace();}}}
}

CustomUnrarCallback.java

package xxx;import com.github.junrar.UnrarCallback;
import com.github.junrar.Volume;/*** 自定义rar文件解压回调类* @author pansh* @since 2021-12-7 16:53:41*/
public class CustomUnrarCallback implements UnrarCallback {@Overridepublic boolean isNextVolumeReady(Volume volume) {return true;}@Overridepublic void volumeProgressChanged(long l, long l1) {}
}

欢迎转载

java解析压缩文件,支持zip,rar,7z压缩格式相关推荐

  1. java压缩文件为rar_java 实现压缩多个文件 成zip/rar 等压缩文件

    一下代码实现的是将多个文件进行压缩,采用的是边压缩边下载的方式 /** * 压缩文件 * @param exportFilePathList * @param response */ public s ...

  2. java解析xml文件的几种方式(DOM解析)

    好久不用的东西,今天居然被面试官问到了.那既然这样,我们就一起回顾下java解析xml文件的几种方式吧. DOM解析 dom解析所需依赖是我们jdk自带的,所以只需要使用jdk为我们提供的接口即可上手 ...

  3. 压缩文件格式介绍zip, rar, gz, tar.gz, tgz, bz2, Z, tar等

    Windows下常见的压缩文件有zip和rar两种, 而linux下有gz, tar.gz, tgz, bz2, Z, tar等. 值得指出的是:打包和压缩是两个概念. linux下最常用的打包程序是 ...

  4. java解析Excel文件的方法

    java解析Excel文件的方法 介绍 1.1 pom依赖 1.2 将数据流转化为可解析的Workbook类型文件 1.3 解析 1.4 Controller层接收前端传递的Excel文件(前端使用E ...

  5. Python将Pandas中Dataframe数据保存为gzip/zip文件:gzip压缩文件、zip压缩文件

    Python将Pandas中Dataframe数据保存为gzip/zip文件:gzip压缩文件.zip压缩文件 目录 Python将Pandas中Dataframe数据保存为gzip/zip文件:gz ...

  6. java 解析 csv 文件

    文章分类:JavaEye 一.貌似有bug,不行用 二.或 三. 的方法 Java代码   import java.io.BufferedReader; import java.io.FileInpu ...

  7. 用正则表达式和java解析csv文件

    用正则表达式和java解析csv文件 作者:弹着钢琴设计  来源:博客园  发布时间:2009-06-15 18:31  阅读:337 次  原文链接   [收藏]   在解析csv文件之前,先来看看 ...

  8. java解析dxf文件_浅析JVM方法解析、创建和链接

    一:前言 上周末写了一篇文章<你知道Java类是如何被加载的吗?>,分析了HotSpot是如何加载Java类的,干脆趁热打铁,本周末再来分析下Hotspot又是如何解析.创建和链接类方法的 ...

  9. java解析xml文件

    使用java解析xml文件,通过dom4j. 代码如下: package com.java.team; import java.io.File; import java.util.ArrayList; ...

  10. java解析Excel文件

    下文介绍java解析Excel文件的方案 前置准备 1.第三方jar包或者Maven配置 org.apache.poi的jar包 Maven配置如下 <groupId>org.apache ...

最新文章

  1. Scala中的/,%,++,--
  2. 【Gym - 101612C】【2017-2018NEERC】Consonant Fencity(状压枚举,预处理)
  3. 理解Java操作数据库原理
  4. mysql 当天创建分区表_mysql8.0 定时创建分区表记录 每天定时创建下一天的分区表...
  5. C++函数和类的封装
  6. Python 语言程序设计(4-1)分支循环语句
  7. Ubuntu18.04 修改IP地址、查看网关、防火墙
  8. DB2数据库的备份还原详解
  9. 上海铭控 第二届“铭控Smart Sensor”奖学金颁奖典礼完美谢幕
  10. Hulu热招 | ADI广告数据和算法团队
  11. android 视频转码需要权限,android 使用 ffmpeg 进行视频转码(一)
  12. redisRDB持久化中dir路径配置问题
  13. 自学python从字符串开始吧
  14. 蓝桥杯真题:小朋友崇拜圈
  15. (论文翻译)AutoEncoder 聚类算法 - DEPICT
  16. P5638 【CSGRound2】光骓者的荣耀
  17. pikachu RCE
  18. EtherCAT总线介绍及从站硬件设计
  19. git中的revert和reset
  20. 洛谷P3853:路标设置【二分,以及本菜的心路历程】

热门文章

  1. 良心杀毒,贴心免费去弹窗(你的Windows杀毒软件有这个功能吗?)
  2. 【VC++学习日志】VCC++学习日志
  3. uni-app时间戳转换日期格式
  4. js时间戳转换日期格式 yyyy-MM-dd hh:mm:ss
  5. python输入矩阵
  6. C++:在VS中release版本下设置断点调试,详细步骤
  7. WKB-LINESTRING格式
  8. Win10家庭版不支持“本地用户和组”,如果要支持需要升级到专业版
  9. CERT-JAVA Atomicity、 Visibility and Atomicity
  10. Star History下载和使用——查看GitHub项目Star走势/趋势图(star统计信息)