当前位置:

首页 > 编程开发 > Java如何解压带密码的zip、rar、7z文件?

Java如何解压带密码的zip、rar、7z文件?

前言在一些日常业务中,会遇到一些琐碎文件需要统一打包到一个压缩包中上传,业务方在后台接收到压缩包后自行解压,然后解析相应文件。而且可能涉及安全保密,因此会在压缩时带上密码,要求后台业务可以指定密码进行解压。应用环境说明:jdk1.8,maven3.x,需要基于java语言实现对zip、rar、7z等常见压缩包的解压工作。首先关于zip和rar、7z等压缩工具和压缩算法就不在此赘述,下面通过一个数据对比,使用上述三种不同的压缩算法,采用默认的压缩方式,看到压缩的文件大小如下:转换成图表看得更直观,如下图:从

本文目录

    前言

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

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

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

    Java如何解压带密码的zip、rar、7z文件?

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

    Java如何解压带密码的zip、rar、7z文件?

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

    实现代码

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

    1、pom.xml

    
        4.0.0
        com.yelang
        7zdemo
        0.0.1-SNAPSHOT
     
        
            
                net.lingala.zip4j
                zip4j
                2.9.0
            
     
            
                net.sf.sevenzipjbinding
                sevenzipjbinding
                16.02-2.01
            
            
                net.sf.sevenzipjbinding
                sevenzipjbinding-all-platforms
                16.02-2.01
            
     
            
                org.tukaani
                xz
                1.9
            
            
                org.apache.commons
                commons-compress
                1.21
            
            
            
            
                org.slf4j
                slf4j-api
                1.7.30
            
            
            
            
                org.apache.commons
                commons-lang3
                3.12.0
            
            
            
            
                fr.opensagres.xdocreport
                xdocreport
                1.0.6
            
            
        
    

    主要依赖的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文档的RandomAccessFile
                randomAccessFile = new RandomAccessFile(rarDir, "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(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 data
                                sizeArray[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 data
                                sizeArray[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 unFile(String rootPath, String sourcePath, String destDirPath, String passWord) {
            Map resultMap = new HashMap();
            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 specified
                result = 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 password
                result = 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文件?

    Java如何解压带密码的zip、rar、7z文件?

    总结:本文采用java语言实现了对zip和rar、7z文件的解压统一算法。并对比了相应的解压速度,支持传入密码进行在线解压。

    本文参考代码在补充内容里,不过代码直接运行有问题,这里进行了调整,主要优化的点如下:

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

    2、zip路径优化

    3、去掉一些无用信息

    4、优化异常信息

    补充

    1.maven引用

    
       net.lingala.zip4j
       zip4j
       2.9.0
    
     
    
       net.sf.sevenzipjbinding
       sevenzipjbinding
       16.02-2.01
    
    
       net.sf.sevenzipjbinding
       sevenzipjbinding-all-platforms
       16.02-2.01
    
     
    
       org.tukaani
       xz
       1.9
    
    
        org.apache.commons
        commons-compress
        1.21
    

    2.实现代码如下

    import fr.opensagres.xdocreport.core.io.IOUtils;
    import net.lingala.zip4j.ZipFile;
    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.lang3.StringUtils;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import java.io.*;
    import java.util.*;
     
     
    public class ZipAndRarTools {
        private static final Logger log = LoggerFactory.getLogger(ZipAndRarTools.class);
     
        /*
        解压zip
        */
        private static String unZip(String rootPath, String sourceRarPath, String destDirPath, String passWord) {
            ZipFile zipFile = null;
     
            try {
     
                if (StringUtils.isNotBlank(passWord)) {
                    zipFile = new ZipFile(filePath, passWord.toCharArray());
                } else {
                    zipFile = new ZipFile(filePath);
                }
                zipFile.extractAll(rootPath + destDirPath);
            } catch (Exception e) {
                log.error("unZip error", e);
                return e.getMessage();
            }
            return "";
        }
     
     
        /*
           解压rar rar5
           */
        private static String unRar(String rootPath, String sourceRarPath, String destDirPath, String passWord) {
             /*final File rar = new File(rootPath + sourceRarPath);
           final File destinationFolder = new File(rootPath + destDirPath);
            destinationFolder.mkdir();
            try {
                Junrar.extract(rar, destinationFolder);
            } catch (Exception e) {
                log.error("unRar error", e);
                return e.getMessage();
            }*/
     
            String rarDir = rootPath + sourceRarPath;
            String outDir = rootPath + destDirPath + File.separator;
            RandomAccessFile randomAccessFile = null;
            IInArchive inArchive = null;
            try {
                // 第一个参数是需要解压的压缩包路径,第二个参数参考JdkAPI文档的RandomAccessFile
                randomAccessFile = new RandomAccessFile(rarDir, "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(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 data
                                sizeArray[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 data
                                sizeArray[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 "";
        }
     
     
        /*
         * 解压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))
                    new SevenZFile(srcFile, passWord.getBytes());
                else
                    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 "";
        }
     
        public static void unFile(String rootPath, String sourcePath, String destDirPath, String passWord) {
            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 specified
                result = unRar(rootPath, sourcePath, destDirPath, passWord);
            } else if (sourcePath.toLowerCase().endsWith(".7z")) {
                //PasswordRequiredException: Cannot read encrypted content from G:\ziptest\11111111.7z without a password
                result = 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", data);
    //        System.out.println(result + "==============");
            return resultMap;
        }
     
     
        public static void main(String[] args) {
            getFileList("G:\\ziptest\\", "测试.zip", "test3333", "密码");
        }
     
    }
    本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系bd@zhengruan.com
    作者最新文章
    编程开发 Java
    相关文章 更多
    Yandex官网入口及网页搜索使用方法
    Yandex官网入口及网页搜索使用方法

    Yandex官网入口是https://www.yondex.net/,该平台支持多语言切换、智能搜索匹配、虚拟键盘变更及实时翻译,提供地图、图片、新闻、购物等垂直服务,并具备账户同步、隐私管理、个性化首页和云存储等功能。

    Java单元测试入门:使用JUnit 5编写第一个测试用例
    Java单元测试入门:使用JUnit 5编写第一个测试用例

    面向初学者的JUnit 5实用入门指南。从测试概念、Maven依赖配置,到手把手编写首个单元测试用例及断言验证,助你掌握Java单元测试的核心流程。

    Java变量未初始化报错解析:局部变量与成员变量默认值差异
    Java变量未初始化报错解析:局部变量与成员变量默认值差异

    深入解析Java中局部变量未初始化编译报错与成员变量自动赋予默认值的机制差异,涵盖JVM内存分配、编译期确定性赋值检查与实际排查修复方案。

    Java获取当前时间并格式化输出:DateTimeFormatter与SimpleDateFormat
    Java获取当前时间并格式化输出:DateTimeFormatter与SimpleDateFormat

    详细讲解在Java中获取当前系统时间并进行格式化输出的两种核心方案:基于Java 8全新日期时间API的DateTimeFormatter与传统遗留的SimpleDateFormat,包含完整代码示例、线程安全机制对比及生产选型建议。

    Java中final与static final常量的定义及初始化规则
    Java中final与static final常量的定义及初始化规则

    深入解析Java中final变量与static final常量的定义、内存语义、初始化时机及合法赋值路径,涵盖编译期常量优化与实战避坑指南。

    Java抽象方法与接口方法的区别及选型建议
    Java抽象方法与接口方法的区别及选型建议

    深入对比Java中抽象类抽象方法与接口方法的语法演进、设计意图及运行期差异,并提供清晰的架构选型决策流程与实战范例。

    Java实现HTTP请求与JSON解析的完整代码示例
    Java实现HTTP请求与JSON解析的完整代码示例

    本文提供Java标准库HttpClient发起HTTP GET/POST请求并结合Jackson进行JSON数据反序列化与序列化的完整代码示例与工程实践指南。

    Java递归出现StackOverflowError的原因分析及栈空间优化方案
    Java递归出现StackOverflowError的原因分析及栈空间优化方案

    详细分析Java递归调用出现StackOverflowError的原因,结合代码说明线程栈、栈帧和递归深度之间的关系,并介绍终止条件排查、迭代改写、减少栈帧开销以及通过-Xss调整JVM栈空间的方法。

    Java空指针异常(NPE)的代码排查与修复实例
    Java空指针异常(NPE)的代码排查与修复实例

    针对Java中常见的NullPointerException(NPE),本文从堆栈日志定位、典型代码触发场景、具体修复代码对比到防御体系进行系统讲解,提供实用且易上手的排查与修复方案。

    selenium上传文件教程本地文件路径设置方法
    selenium上传文件教程本地文件路径设置方法

    深入解析Selenium处理文件上传的技术细节,涵盖标准HTML控件的路径直接注入法与非标准控件的系统级模拟方案,提供Windows与Linux环境下的路径设置最佳实践及常见异常排查。

    查看更多
    精品专题 更多
    装机必备
    装机必备

    正软商城装机必备专区,精选办公、浏览器、安全防护、影音播放、压缩解压、设计创作和系统工具等电脑常用正版软件,帮助用户快速完成新电脑软件配置。

    Windows
    Windows

    正软商城Windows软件专区,汇集适用于Windows电脑的办公、设计、安全防护、影音播放、开发工具和系统优化软件,提供软件介绍、系统要求、正版授权及购买下载服务。

    PDF教程
    PDF教程

    正软商城PDF教程频道提供PDF编辑、转换、合并、拆分、压缩及格式处理方法,同时介绍常用PDF软件和工具的使用技巧。

    Mac软件 更多
    Qoder
    Qoder
    Windows / macOS / Linux / HarmonyOS

    Qoder智能体工作台将编程任务、项目知识整理和自动化集中处理。本页介绍任务执行、Repo Wiki与结果审阅,区分Qoder IDE、系统安装选项和账户套餐,并提供官方下载入口。

    讯飞智作 网页版
    讯飞智作 网页版
    Windows/ macOS/ Linux

    讯飞智作是一款基于语音合成技术、虚拟人驱动技术与数字人形象声音构建能力的 AI 数字人音视频创作平台。

    火山引擎 网页版
    火山引擎 网页版
    Windows/ macOS/ Linux

    火山引擎是字节跳动旗下企业级云与AI服务平台。聚焦大模型核心能力,依托字节自研豆包多模态大模型,凭借火山方舟一站式平台,提供模型精调、推理部署、智能应用搭建等全链路服务,结合高性能AI算力,助力各行业快速落地大模型数字化与智能化应用。

    WINDOWS 更多
    Qoder
    Qoder
    Windows / macOS / Linux / HarmonyOS

    Qoder智能体工作台将编程任务、项目知识整理和自动化集中处理。本页介绍任务执行、Repo Wiki与结果审阅,区分Qoder IDE、系统安装选项和账户套餐,并提供官方下载入口。

    讯飞智作 网页版
    讯飞智作 网页版
    Windows/ macOS/ Linux

    讯飞智作是一款基于语音合成技术、虚拟人驱动技术与数字人形象声音构建能力的 AI 数字人音视频创作平台。

    火山引擎 网页版
    火山引擎 网页版
    Windows/ macOS/ Linux

    火山引擎是字节跳动旗下企业级云与AI服务平台。聚焦大模型核心能力,依托字节自研豆包多模态大模型,凭借火山方舟一站式平台,提供模型精调、推理部署、智能应用搭建等全链路服务,结合高性能AI算力,助力各行业快速落地大模型数字化与智能化应用。