Java 解压rar文件的两种方法

方法一

 private static void extractRar(String rarPath, String destDir) throws IOException, RarException {
        File dstDiretory = new File(destDir);
        if (!dstDiretory.exists()) {
            dstDiretory.mkdirs();
        }

        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(destDir + 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(destDir + 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();

    }

    //判断文件名有没有正则表达式
    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;
    }
<groupId>com.github.junrar</groupId>
<artifactId>junrar</artifactId>

方法二

 /**
     * 采用命令行方式解压文件
     *
     * @param rarPath 压缩文件路径
     * @param destDir 解压结果路径
     * @param cmdPath WinRAR.exe的路径,也可以在代码中写死
     * @return
     */
    public static boolean realExtract(String rarPath, String destDir, String cmdPath) {
        File rarFile = new File(rarPath);
        // 解决路径中存在/..格式的路径问题
        destDir = new File(destDir).getAbsoluteFile().getAbsolutePath();
        while (destDir.contains("..")) {
            String[] sepList = destDir.split("\\\\");
            destDir = "";
            for (int i = 0; i < sepList.length; i++) {
                if (!"..".equals(sepList[i]) && i < sepList.length - 1 && "..".equals(sepList[i + 1])) {
                    i++;
                } else {
                    destDir += sepList[i] + File.separator;
                }
            }
        }
        boolean bool = false;
        if (!rarFile.exists()) {
            return false;
        }
        // 开始调用命令行解压,参数-o+是表示覆盖的意思
        String cmd = cmdPath + " X -o+ " + rarFile + " " + destDir;
        System.out.println(cmd);
        try {
            Process proc = Runtime.getRuntime().exec(cmd);
            if (proc.waitFor() != 0) {
                if (proc.exitValue() == 0) {
                    bool = false;
                }
            } else {
                bool = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        rarFile.delete();
        return bool;
    }
  • 6
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Java自身并不支持解压RAR文件,需要使用第三方库来实现。 我推荐使用Junrar这个库来解压RAR文件,它是一个开源库,可以在Github上找到它的代码和文档。 以下是一个简单的示例代码,演示如何使用Junrar库来解压RAR文件: ```java import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.List; import com.github.junrar.Archive; import com.github.junrar.exception.RarException; import com.github.junrar.impl.FileVolumeManager; import com.github.junrar.rarfile.FileHeader; public class RarExtractor { public static void extract(String filePath, String outputFolder) throws IOException, RarException { Archive archive = null; try { archive = new Archive(new FileVolumeManager(new File(filePath))); if (archive != null) { archive.getMainHeader().print(); List<FileHeader> headers = archive.getFileHeaders(); for (FileHeader header : headers) { if (header.isDirectory()) { continue; } File file = new File(outputFolder + File.separator + header.getFileNameString().trim()); if (!file.exists()) { if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } file.createNewFile(); } OutputStream os = null; try { os = new FileOutputStream(file); archive.extractFile(header, os); } finally { if (os != null) { os.close(); } } } } } finally { if (archive != null) { archive.close(); } } } public static void main(String[] args) { String filePath = "path/to/rar/file.rar"; String outputFolder = "output/folder/path"; try { extract(filePath, outputFolder); } catch (IOException e) { e.printStackTrace(); } catch (RarException e) { e.printStackTrace(); } } } ``` 你需要将上述代码中的 `filePath` 和 `outputFolder` 替换成你自己的RAR文件路径和输出目录路径。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值