rar解压版本:需要使用0.7,其他版本尝试了,不行,而且rar压缩的时候,也需要指定rar4,高版本不支持

        <!--解压rar压缩--><dependency><groupId>com.github.junrar</groupId><artifactId>junrar</artifactId><version>0.7</version></dependency>
//路由方法
private void fileUnCompressUtil(File file,String realPath, String randomFileName, String fileType) {String filePath = realPath + randomFileName;try {//解压.zip格式文件if (fileType == CompressType.ZIP.name()) {CompressUtils.unzip(filePath);}//rar格式解压,需要一个后缀名以.rar结尾的文件if (fileType == CompressType.RAR.name()) {CompressUtils.unPackRar(file,filePath.substring(0,filePath.lastIndexOf(".")));}} catch (ZipException e) {logger.error("解压异常:{}", filePath);CoreCommonUtils.raiseRuntimeException(e);}}

工具类:

/*** Qiangungun.com Inc.* <p/>* Copyright (c) 2014-2016 All Rights Reserved.*/
package com.qiangungun.boss.web.common;import com.github.junrar.Archive;
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;/*** CompressUtil.<br />** Created by ghost on 2016/5/26.*/
public class CompressUtils {private static final Logger logger = LoggerFactory.getLogger(CompressUtils.class);/*** 使用给定密码解压指定的ZIP压缩文件到指定目录* <p>* 如果指定目录不存在,可以自动创建,不合法的路径将导致异常被抛出* @param zip 指定的ZIP压缩文件* @param dest 解压目录* @param passwd ZIP文件的密码* @return 解压后文件数组* @throws ZipException 压缩文件有损坏或者解压缩失败抛出*/public static File[] unzip(String zip, String dest, String passwd) throws ZipException {File zipFile = new File(zip);if(StringUtils.isEmpty(dest)){dest = zipFile.getParentFile().getAbsolutePath();}return unzip(zipFile, dest, passwd);}/*** 带加密的解压文件<br/>** @param zip* @param passwd* @return* @throws ZipException*/public static File[] unzip(String zip, String passwd) throws ZipException {return unzip(zip, zip.substring(0,zip.lastIndexOf("\\")), passwd);}/*** 直接解压文件<br/>** @param zip* @return* @throws ZipException*/public static File[] unzip(String zip) throws ZipException {return unzip(zip, null, null);}/*** 直接解压文件<br/>** @param zip* @return* @throws ZipException*/public static File[] unzip(File zip) throws ZipException {return unzip(zip, zip.getParentFile().getAbsolutePath(), null);}/*** 使用给定密码解压指定的ZIP压缩文件到指定目录* <p>* 如果指定目录不存在,可以自动创建,不合法的路径将导致异常被抛出* @param zipFile 指定的ZIP压缩文件* @param dest 解压目录* @param passwd ZIP文件的密码* @return  解压后文件数组* @throws ZipException 压缩文件有损坏或者解压缩失败抛出*/public static File[] unzip(File zipFile, String dest, String passwd)throws ZipException {ZipFile zFile = new ZipFile(zipFile);zFile.setFileNameCharset("GBK");if (!zFile.isValidZipFile()) {throw new ZipException("压缩文件不合法,可能被损坏.");}dest = dest + "//" + zipFile.getName().substring(0,zipFile.getName().lastIndexOf("."));File destDir = new File(dest);if (!destDir.exists()) {destDir.mkdir();}if (zFile.isEncrypted()) {zFile.setPassword(passwd.toCharArray());}try {zFile.extractAll(dest);}catch (ZipException e){logger.error("解压文件错误,删除目录下的文件。",e);if(deleteDir(destDir)){logger.info("解压错误,删除目录成功。");}throw  e;}List<net.lingala.zip4j.model.FileHeader> headerList = zFile.getFileHeaders();List<File> extractedFileList = new ArrayList<File>();for(net.lingala.zip4j.model.FileHeader fileHeader : headerList) {if (!fileHeader.isDirectory()) {extractedFileList.add(new File(destDir,fileHeader.getFileName()));}}File[] extractedFiles = new File[extractedFileList.size()];extractedFileList.toArray(extractedFiles);return extractedFiles;}/*** 删除目录或文件下面的全部文件* @param destDir* @return*/private static boolean deleteDir(File destDir) {if(destDir.isDirectory()){String[] childrens = destDir.list();if(null != childrens){for (String children : childrens){deleteDir(new File(children));}}}destDir.delete();return true;}public static Boolean zipFiles(List<File> fileList, ZipFile zipFile, String password){logger.info("开始压缩文件:"+fileList.size());try {ArrayList<File> filesToAdd = new ArrayList<File>();for (File file :fileList){filesToAdd.add(file);}ZipParameters parameters = new ZipParameters();parameters.setEncryptFiles(true);parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_STANDARD);parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE); // set compression method to deflate compressionparameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);parameters.setPassword(password);zipFile.addFiles(filesToAdd, parameters);} catch (ZipException e) {logger.error("压缩文件失败",e);return  false;}return  true;}public static Boolean zipFiles(List<File> fileList, ZipFile zipFile){logger.info("开始压缩文件:"+fileList.size());try {ArrayList<File> filesToAdd = new ArrayList<File>();for (File file :fileList){filesToAdd.add(file);}ZipParameters parameters = new ZipParameters();parameters.setEncryptFiles(false);parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE); // set compression method to deflate compressionparameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);zipFile.addFiles(filesToAdd, parameters);} catch (ZipException e) {logger.error("压缩文件失败",e);return  false;}return  true;}public static File doGzipCompressFile(String inFileName) {try {logger.info("开始压缩文件gz");String outFileName = inFileName + ".gz";GZIPOutputStream out = null;try {out = new GZIPOutputStream(new FileOutputStream(outFileName));} catch(FileNotFoundException e) {logger.error("Could not create file"+outFileName);} catch (IOException e) {e.printStackTrace();}FileInputStream in = null;try {in = new FileInputStream(inFileName);} catch (FileNotFoundException e) {logger.error("File not found. " + inFileName);}logger.info("Transfering bytes from input file to GZIP Format.");byte[] buf = new byte[1024];int len;while((len = in.read(buf)) > 0) {out.write(buf, 0, len);}in.close();logger.info("Completing the GZIP file");out.finish();out.close();return new File(outFileName);} catch (IOException e) {e.printStackTrace();}return null;}public static File doUnGzipcompressFile(String gzip) {try {if (!getExtension(gzip).equalsIgnoreCase("gz")) {logger.error("File name must have extension of \".gz\"");}logger.info("Opening the compressed file.");GZIPInputStream in = null;try {in = new GZIPInputStream(new FileInputStream(gzip));} catch(FileNotFoundException e) {logger.error("File not found. " + gzip);}logger.info("Open the output file.");String outFileName = getFileName(gzip);FileOutputStream out = null;try {out = new FileOutputStream(outFileName);} catch (FileNotFoundException e) {logger.error("Could not write to file. " + outFileName);}logger.info("Transfering bytes from compressed file to the output file.");byte[] buf = new byte[1024];int len;while((len = in.read(buf)) > 0) {out.write(buf, 0, len);}logger.info("Closing the file and stream");in.close();out.close();return new File(outFileName);} catch (IOException e) {e.printStackTrace();}return null;}/*** rar文件解压(不支持有密码的压缩包)** @param rarFile  rar压缩包* @param destPath 解压保存路径*/public static void unPackRar(File rarFile, String destPath) {try (Archive archive = new Archive(rarFile)) {if (null != archive) {com.github.junrar.rarfile.FileHeader fileHeader = archive.nextFileHeader();File file = null;while (null != fileHeader) {// 防止文件名中文乱码问题的处理String fileName = fileHeader.getFileNameW().isEmpty() ? fileHeader.getFileNameString() : fileHeader.getFileNameW();if (fileHeader.isDirectory()) {//是文件夹file = new File(destPath + File.separator + fileName);file.mkdirs();} else {//不是文件夹file = new File(destPath + File.separator + fileName.trim());if (!file.exists()) {if (!file.getParentFile().exists()) {// 相对路径可能多级,可能需要创建父目录.file.getParentFile().mkdirs();}file.createNewFile();}FileOutputStream os = new FileOutputStream(file);archive.extractFile(fileHeader, os);os.close();}fileHeader = archive.nextFileHeader();}}} catch (Exception e) {logger.error("unpack rar file fail....", e.getMessage(), e);}}//    //解压.rar文件
//    public static void unRar(String sourceFile, String outputDir) throws Exception {
//        Archive archive = null;
//        FileOutputStream fos = null;
//        File file = new File(sourceFile);
//        try {
//            archive = new Archive(file);
//            com.github.junrar.rarfile.FileHeader fh = archive.nextFileHeader();
//            int count = 0;
//            File destFileName = null;
//            while (fh != null) {
//                System.out.println((++count) + ") " + fh.getFileNameString());
//                String compressFileName = fh.getFileNameString().trim();
//                destFileName = new File(outputDir + "/" + compressFileName);
//                if (fh.isDirectory()) {
//                    if (!destFileName.exists()) {
//                        destFileName.mkdirs();
//                    }
//                    fh = archive.nextFileHeader();
//                    continue;
//                }
//                if (!destFileName.getParentFile().exists()) {
//                    destFileName.getParentFile().mkdirs();
//                }
//                fos = new FileOutputStream(destFileName);
//                archive.extractFile(fh, fos);
//                fos.close();
//                fos = null;
//                fh = archive.nextFileHeader();
//            }
//
//            archive.close();
//            archive = null;
//        } catch (Exception e) {
//            throw e;
//        } finally {
//            if (fos != null) {
//                try {
//                    fos.close();
//                    fos = null;
//                } catch (Exception e) {
//                    //ignore
//                }
//            }
//            if (archive != null) {
//                try {
//                    archive.close();
//                    archive = null;
//                } catch (Exception e) {
//                    //ignore
//                }
//            }
//        }
//    }public static String getExtension(String f) {String ext = "";int i = f.lastIndexOf('.');if (i > 0 &&  i < f.length() - 1) {ext = f.substring(i+1);}return ext;}public static String getFileName(String f) {String fname = "";int i = f.lastIndexOf('.');if (i > 0 &&  i < f.length() - 1) {fname = f.substring(0,i);}return fname;}
}

解压zip、rar、gz格式文件相关推荐

  1. Android解压zip rar 7z文件

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

  2. 深度学习制作数据集的部分代码实现(解压zip、生成json文件)

    1.当数据集是压缩包时,需要解压成图片文件 import zipfile def unzip_data(src_path,target_path):'''解压原始数据集,将src_path路径下的zi ...

  3. java解压加密的7z格式文件

    引言 最近在 项目中需要解压带有密码的.7z文件,然后获得里面的数据,之前都是zip 文件没有接触过解压7z类型的 文件,在这分享一下解压工具类,该 工具类可以同时解压带有密码的7z文件和zip文件. ...

  4. java解压zip包_Java中文件的压缩与解压,每天进步一点点系列

    使用java.util.zip包,实现文件的压缩与解压,并提供了下载方法 注意 无论是调用createNewFile()创建文件,还是在创建输出流时由输出流负责创建文件,都必须保证父路径已经存在,否则 ...

  5. linux解压zip同时重命名文件

    unzip a.zip 解压文件以a为文件名 unzip a.zip -d b 解压文件重命名为b

  6. 使用Python解压zip、rar文件

    解压 zip 文件 基本解压操作 import zipfile''' 基本格式:zipfile.ZipFile(filename[,mode[,compression[,allowZip64]]]) ...

  7. Android 解压zip文件你知道多少?

    对于Android常用的压缩格式ZIP,你了解多少? Android的有两种解压ZIP的方法,你知道吗? ZipFile和ZipInputStream的解压效率,你对比过吗? 带着以上问题,现在就开始 ...

  8. java读取zip文件名_java无需解压zip压缩包直接读取包内的文件名(含中文)

    java自带了java.util.zip工具可以实现在不解压zip压缩包的情况下读取包内文件的文件名:(注:只能是ZIP格式的,rar我试了不行)代码如下: public static String ...

  9. java 万能解压zip工具类

    项目中有需要解压zip包,但是网上搜了下,工具类过于局限,故整理一个万能的解压zip的工具类.如果大家有更好的方式欢迎交流! 工具类1: /*** 解压文件到指定目录** @param zipFile ...

最新文章

  1. AttributeError: module 'tensorflow' has no attribute 'random_normal'
  2. 剖析IntentService的运作机理
  3. Qute模板与Quarkus
  4. 【c++】22. STL容器的底层实现详解
  5. 深入理解Hadoop集群和网络
  6. 苹果降低应用商店收入一半分成、Twitter视频分享功能 Fleet、百度36亿美元收购 YY|Decode the Week...
  7. Android之Camera介绍
  8. react前端显示图片_在 React 中使用 SVG 图标组件
  9. TensorFlow:卷积神经网络
  10. oracle巡检项,Oracle数据库巡检参考项
  11. JavaScript 实现Map效果
  12. 南瑞科技服务器型号,南瑞--NSC通讯概述
  13. 机器学习数学基础之高数篇——函数极限和导数(python版)
  14. CAN总线学习总结2——CAN错误及CAN busoff处理机制
  15. Tomcat网站根目录设置
  16. 阿里云跨云迁移工具案例实践:华为云迁移到阿里云
  17. PLG日志平台搭建: Promtail + Loki + Grafana 全步骤
  18. 2个阶乘什么意思_两个阶乘符号连在一起是什么意思
  19. tmall API接口关键字获取商品数据
  20. 论文投稿指南——SCI选刊

热门文章

  1. 外地人在上海驾照到期可以异地办理么?
  2. 2017首届江苏虚拟现实发展大会倒计时,一大波大咖带着干货即将“来袭”
  3. python Gooey doesn‘t currently support top level required arguments when subparsers are present.
  4. 信息检索——常见名词缩写汇总
  5. 图形推理1000题pdf_图形推理:画“箭头”,瞬秒立体题!
  6. go语言工具_easyjson
  7. 【Android】Long monitor contention with owner ...
  8. VMware15安装macOS Mojave 10.14.6(18G87)
  9. 关闭WordPress站内容搜,杜绝违禁词在站内恶意搜索
  10. PCB设计(四层板初步)