使用java解压缩zip和rar4

该文章介绍了一种使用Java进行ZIP和RAR文件解压缩的方法。通过引入ApachePOI和Junrar库,创建了一个工具类,分别实现了对ZIP和RAR文件的解压功能。在解压过程中,使用了文件输入/输出流将压缩内容写入目标文件或创建新的文件夹。测试类展示了如何调用这些方法进行实际操作。
摘要由CSDN通过智能技术生成

使用java解压缩zip和rar4

注意:rar5无法解压
环境准备:
导入依赖

<dependency>
    <groupId>com.github.junrar</groupId>
    <artifactId>junrar</artifactId>
    <version>4.0.0</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.17</version>
</dependency>

创建工具类

public class fileZipUtil {
    /**
     * zip文件解压
     * @param inputFile  待解压文件夹/文件
     * @param destDirPath  解压路径
     */
    public static void unZipFiles(String inputFile,String destDirPath) throws Exception {
        File srcFile = new File(inputFile);//获取当前压缩文件
        // 判断源文件是否存在
        if (!srcFile.exists()) {
            throw new Exception(srcFile.getPath() + "所指文件不存在");
        }
        ZipFile zipFile = new ZipFile(srcFile, Charset.forName("GBK"));//创建压缩文件对象
        //开始解压
        Enumeration<?> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) entries.nextElement();
            // 如果是文件夹,就创建个文件夹
            if (entry.isDirectory()) {
                String dirPath = destDirPath + "/" + entry.getName();
                srcFile.mkdirs();
            } else {
                // 如果是文件,就先创建一个文件,然后用io流把内容copy过去
                File targetFile = new File(destDirPath + "/" + entry.getName());
                // 保证这个文件的父文件夹必须要存在
                if (!targetFile.getParentFile().exists()) {
                    targetFile.getParentFile().mkdirs();
                }
                targetFile.createNewFile();
                // 将压缩文件内容写入到这个文件中
                InputStream is = zipFile.getInputStream(entry);
                FileOutputStream fos = new FileOutputStream(targetFile);
                int len;
                byte[] buf = new byte[1024];
                while ((len = is.read(buf)) != -1) {
                    fos.write(buf, 0, len);
                }
                // 关流顺序,先打开的后关闭
                fos.close();
                is.close();
            }
        }
    }

    /**
     * 解压RAR压缩文件到指定路径
     * @param rarFile RAR压缩文件
     * @param dstDir 解压到的文件夹路径
     */
    public static void unRarFile(String rarPath, String dstDir) throws Exception {

        File dstDiretory = new File(dstDir);
        if (!dstDiretory.exists()) {
            dstDiretory.mkdirs();
        }
        try {
            File rarFile= new File(rarPath);
            Archive archive = new Archive(new FileInputStream(rarFile));
            List<FileHeader> fileHeaders = archive.getFileHeaders();
            for (FileHeader fileHeader : fileHeaders) {
                if (fileHeader.isDirectory()) {
                    String fileName=  fileHeader.getFileNameW();
                    if(!existZH(fileName)){
                        fileName = fileHeader.getFileNameString();
                    }
                    File dir = new File(dstDir + File.separator + fileName);
                    if (!dir.exists()){
                        dir.mkdirs();
                    }
                } else {
                    String fileName=  fileHeader.getFileNameW().trim();
                    if(!existZH(fileName)){
                        fileName = fileHeader.getFileNameString().trim();
                    }
                    File file = new File(dstDir + File.separator + fileName);
                    try {
                        if (!file.exists()) {
                            if (!file.getParentFile().exists()) {
                                file.getParentFile().mkdirs();
                            }
                            file.createNewFile();
                        }
                        FileOutputStream os = new FileOutputStream(file);
                        archive.extractFile(fileHeader, os);
                        os.close();
                    } catch (Exception ex) {
                        throw ex;
                    }
                }
            }
            archive.close();
        } catch (Exception e) {
            throw e;
        }
    }
    public static boolean existZH(String str) {
        String regEx = "[\\u4e00-\\u9fa5]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        while (m.find()) {
            return true;
        }
        return false;
    }
    }

创建测试类

//使用main方法进行测试
public static void main(String[] args) {
    try {
        String filepath = "D:\\java\\img.zip";//压缩文件存放的位置
        String newpath="D:\\java\\zipTest2";//解压后的文件存放的位置
        //获取最后一个.的位置
        int lastIndexOf = filepath.lastIndexOf(".");
        //获取文件的后缀名 .jpg
        String suffix = filepath.substring(lastIndexOf);
        if(suffix.equals(".zip")){
            unZipFiles(filepath,newpath);

        }else if(suffix.equals(".rar")){
            unRarFile(filepath,newpath);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值