递归解压rar压缩文件

本文介绍了一个使用Java实现的递归解压RAR文件的方法,通过引入`junrar`库,能够处理包含子目录和多个RAR压缩包的情况。代码中包括了检查文件是否存在中文字符的功能,确保解压过程的正确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

依赖
<dependency>
    <groupId>com.github.junrar</groupId>
    <artifactId>junrar</artifactId>
    <version>3.0.0</version>
</dependency>

/**
 * @Author Math
 * @Description 递归解压rar文件
 * @Date  2022/8/26
 * @Version 1.0
 * @Param [file, destDirPath]
 * @Param [要解压的文件, 解压后路径]
 * @return void
 **/
public static void unRar(File file, String destDirPath) throws Exception {
    Archive archive = null;
    File destFileName;
    FileOutputStream fos;
    if (file != null && file.length() > 0) {
        archive = new Archive(new FileVolumeManager(file));
    }
    if (archive == null) {
        throw new Exception("请检查上传rar包版本是否为5.0以下");
    }
    FileHeader fh;
    while ((fh = archive.nextFileHeader()) != null) {
        String fileName = fh.getFileNameW().trim();
        if (!existChinese(fileName)) {
            fileName = fh.getFileNameString().trim();
        }
        fileName = fileName.replaceAll("\\\\", "/");
        destFileName = new File(destDirPath + "/" + fileName);
        if (fh.isDirectory()) {
            continue;
        }
        if (!destFileName.getParentFile().exists()) {
            destFileName.mkdirs();
        }
        fos = new FileOutputStream(destFileName);
        archive.extractFile(fh, fos);
        if (fos != null) {
            fos.close();
        }
        String name = fileName.substring(0, fileName.lastIndexOf("."));
        if (fileName.contains(".rar")) {
            unRar(destFileName, destDirPath + "/" + name);
            destFileName.delete();
            continue;
        }
    }
    if (archive != null) {
        archive.close();
    }
}
/**
 * @Author Math
 * @Description 检测中文
 * @Date  2022/8/26
 * @Version 1.0
 * @Param [str]
 * @return boolean
 **/
public static boolean existChinese(String str) {
    String regEx = "[\\u4e00-\\u9fa5]";
    Pattern p = Pattern.compile(regEx);
    Matcher m = p.matcher(str);
    while (m.find()) {
        return true;
    }
    return false;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值