利用Apache的commons-compress包实现对文件的压缩和解压

所需jar包:(代码中用到了文件拷贝,因此导入了commons-io包)

<dependency><groupId>org.apache.commons</groupId><artifactId>commons-compress</artifactId><version>1.18</version>
</dependency>
<dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.5</version>
</dependency>

具体实现:

public class ZipFileUtil {/*** 压缩文件* @param srcFilePath 需要压缩的文件路径* @param zipFilePath 压缩后文件(全路径的文件,例如:E:/test.zip)* @throws Exception*/public static void compressFilesZip(String srcFilePath, String zipFilePath)throws Exception{Date start = new Date();System.out.println("压缩文件路径为:" + srcFilePath);if (srcFilePath == null || "".equals(srcFilePath.trim())){throw new Exception("压缩文件路径不能为空");}File srcFile = new File(srcFilePath);if (!srcFile.exists()){throw new Exception("文件目录不存在!");}File []files = srcFile.listFiles();if (files == null || files.length <= 0){throw new Exception("需压缩文件目录为空!");}List<String> allFileDir = getAllFiles(srcFilePath); //获取所有文件目录File resultZipFile = new File(zipFilePath);try(ZipArchiveOutputStream zipArchiveOutputStream = new ZipArchiveOutputStream(resultZipFile)) {zipArchiveOutputStream.setUseZip64(Zip64Mode.AsNeeded);//将每个文件用ZipArchiveEntry封装再写到压缩文件中
            addAllFilesToZip(srcFilePath, allFileDir, zipArchiveOutputStream);zipArchiveOutputStream.finish();}Date endDate = new Date();System.out.println("压缩执行时间为:" + (endDate.getTime()-start.getTime()));}/*** 把文件添加到压缩包中* @param srcFilePath* @param allFileDir* @param zipArchiveOutputStream* @throws IOException*/private static void addAllFilesToZip(String srcFilePath, List<String> allFileDir, ZipArchiveOutputStream zipArchiveOutputStream) throws IOException {for (String fileDir : allFileDir) {File file = new File(fileDir);if (file.isDirectory()) {    //若是目录则不压缩continue;}//获取要压缩文件的相对路径,再将相对路径设置到压缩目录中完成对文件夹的压缩String fileName = getFileRelativePathName(srcFilePath, fileDir);ZipArchiveEntry zipArchiveEntry = new ZipArchiveEntry(file, fileName);zipArchiveOutputStream.putArchiveEntry(zipArchiveEntry);try (InputStream inputStream = new BufferedInputStream(new FileInputStream(file))) {IOUtils.copy(inputStream, zipArchiveOutputStream);}zipArchiveOutputStream.closeArchiveEntry();}}/*** 把zip解压到指定目录* @param zipFilePath 压缩包路径* @param saveFileDir 解压到目录*/public static void decompressZip(String zipFilePath, String saveFileDir)throws Exception{System.out.println("解压文件为:" + zipFilePath);Date start = new Date();if (saveFileDir == null || "".equals(saveFileDir.trim())){throw new Exception("解压目录不能为空");}File zipFile = new File(zipFilePath);if (!zipFile.exists()){throw new Exception("需解压的文件不存在!");}//解压目录不存在创建目录File saveFilePath = new File(saveFileDir);if (!saveFilePath.exists()){saveFilePath.mkdirs();}try(InputStream inputStream = new FileInputStream(zipFile)){try (ZipArchiveInputStream zipArchiveInputStream = new ZipArchiveInputStream(inputStream)) {ArchiveEntry archiveEntry = null;while ((archiveEntry = zipArchiveInputStream.getNextEntry()) != null){//解压时拷贝文件目录如若不存在则创建目录String catalog = saveFileDir + "/" + archiveEntry.getName();catalog = catalog.substring(0,catalog.lastIndexOf("/"));File catalogFile = new File(catalog);if (!catalogFile.exists()){catalogFile.mkdirs();}try(OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(new File(saveFileDir,archiveEntry.getName())))){IOUtils.copyLarge(zipArchiveInputStream,outputStream);}finally {IOUtils.closeQuietly();}}}}Date endDate = new Date();System.out.println("解压执行时间为:" + (endDate.getTime()-start.getTime()));}/*** 获取相对路径* @param dir* @param path* @return*/public static String getFileRelativePathName(String dir, String path){if (!dir.endsWith("/")){dir = dir + "/";}String temp = path.substring(dir.length());return temp;}/*** 递归获取目录中所有文件* @param dir* @return*/public static List<String> getAllFiles(String dir){List<String> allDirs = new ArrayList<>();File srcFile = new File(dir);File files[] = srcFile.listFiles();for (File file : files){if (file.isDirectory()){allDirs.add(file.getPath());allDirs.addAll(getAllFiles(file.getPath()));}else {allDirs.add(file.getPath());}}return allDirs;}//测试压缩与解压public static void main(String args[])throws Exception{compressFilesZip("E:/123","E:/123ABC.zip");decompressZip("E:/123ABC.zip","E:/1");}
}

转载于:https://www.cnblogs.com/xiao-OvO-/p/11094052.html

java压缩解压文件相关推荐

  1. java压缩解压文件工具类

    controller中使用 @PostMapping(value = "/importZip")public Result<?> importExcel(HttpSer ...

  2. java代码实现解压文件_Java压缩/解压文件的实现代码

    用java压缩/解压文件: import java.io.*; import java.awt.*; import java.awt.event.*; import java.util.*; impo ...

  3. 测试掌握的Linux解压,轻松掌握Linux压缩/解压文件的方法

    对于在Linux下解压大型的*.zip文件,相信大家一般都会通过使用winrar直接在smb中来进行解压的操作,虽然说最终可能能够解压但有时候会存在解压时间长或者网络原因出错等故障的情况出现.那么有没 ...

  4. 命令行下(bat)使用 Lhaplus 自动 压缩 解压文件 (含参数设定说明)

    命令行下(bat)使用 Lhaplus 自动 压缩 解压文件,参数设定 https://mp.csdn.net/console/editor/html/104400832 ■前言 准备测试数据,要压缩 ...

  5. WinRAR压缩解压文件

    使用WinRAR压缩管理器压缩解压文件详细步骤如下: ■ 压缩文件 ① 鼠标右键需要压缩的文件,点击"添加到压缩文件",具体操作步骤如图所示: ② 压缩后的对应文件压缩包会显示在桌 ...

  6. zip包怎么解压oracle,使用jar与zip压缩解压文件的区别

    使用jar命令压缩和解压文件不会继承原来的权限,切记! 而使用zip/unzip压缩解压文件则会保留文件原来的权限等信息,因此使用压缩解压的时候尽量使用专业的工具 下面是测试内容和结果: 1.首先确认 ...

  7. android zip解压出错,常见的压缩解压文件出错解决办法

    您是否遇到过精力了好久下回来的压缩吧,结果在解压过程中出现错误的情况呢?比如说此解压失败或压缩文件文件已经损坏?导致解压文件失败.如果遇到这种问题,那就试试常见的压缩解压文件出错解决办法吧.凡事求人不 ...

  8. tar多线程压缩解压文件

    tar多线程压缩解压文件 tar -czvf a.tar.gz ./* 测试每分钟压缩包a.tar.gz增长大约300M 安装多线程程序 yum -y install pigz 实测,4核的机器,2G ...

  9. java 7zip解压_Apache Commons Compress介绍-JAVA压缩解压7z文件

    7zip(下面简称7z)是由Igor Pavlov所开发的一种压缩格式,主要使用的压缩算法是LZMA/LZMA2.7z是一种压缩比非常高的格式,这与其压缩算法LZMA有直接关系,所以很多大文件都是用7 ...

  10. java 压缩/解压【tar.gz】

    环境 操作系统:win7 java:jdk7 第三方包:commons-compress-1.14.jar 需求 不管是文件夹还是常规文件,实现基本的打包压缩. 思路: ①先把需要压缩的文件,打包成. ...

最新文章

  1. Laravel: 基础篇
  2. java 显式锁_Java 实现一个自己的显式锁Lock(有超时功能)
  3. python 打开 pip_python pip
  4. 在linux中安装rpm包
  5. 厚积薄发,丰富的公用类库积累,助你高效进行系统开发(2)(转)
  6. chrome 获取剪贴板内容_Chrome 开发者工具的11 个高级使用技巧
  7. [19/04/11-星期四] 多线程_并发协作(生产者/消费者模式_2种解决方案(管程法和信号灯法))...
  8. 一维条形码识别c语言_条形码的优点
  9. Master HA源码解析
  10. js `` 手机不支持
  11. c语言单片机彩灯程序设计,用C语言实现键控彩灯系统
  12. 基于JAVA+SpringMVC+Mybatis+MYSQL的培训中心管理系统
  13. [Android] SharedPreference的使用
  14. php底层深度探索(3) ---Apache启动阶段分析 王泽宾
  15. ABBYY FineReader PDF for Mac(多功能PDF转换工具)
  16. Ubuntu常用软件安装
  17. 学习python自动化测试的好处
  18. 刷新网页定位到特定位置
  19. 我用3天时间,整理了几十个项目的Python资料
  20. portal认证 java_华为5700交换机通过外部开源protal和本地aaa用户认证的一些问题

热门文章

  1. Adhesive框架系列文章--报警服务使用实践
  2. primary key and Foreign Key someCopyIdea
  3. 如何用R语言做词云图,以某部网络小说为例
  4. powerdesigner 数据类型与数据库数据类型对应
  5. shell脚本学习(3)文件判断
  6. Win10微软帐户切换不回Administrator本地帐户的解决方法--(转,虽转但亲测有效)
  7. FFT,NTT 专题
  8. 阻塞模式下的超时等待
  9. React 16.7.0-alpha hooks 之规则
  10. 不拦截Request!基于WKWebView的API实现Hybrid容器