引入依赖

        <dependency>
            <groupId>com.github.junrar</groupId>
            <artifactId>junrar</artifactId>
            <version>1.0.0</version>
        </dependency>

代码

    public static void unRar(String rarFilePath, String destDirPath) throws RarException, IOException {
        Archive archive = new Archive(new File(rarFilePath));
        // 遍历 RAR 文件中的所有文件
        FileHeader fileHeader;
        while ((fileHeader = archive.nextFileHeader()) != null) {
            File outputFile = new File(destDirPath + File.separator + fileHeader.getFileNameW());
            if (!FileUtil.exist(outputFile)){
                FileUtil.mkParentDirs(outputFile);
            }
            if (!fileHeader.isDirectory()){
                FileOutputStream fos = new FileOutputStream(outputFile);
                archive.extractFile(fileHeader, fos);
                fos.close();
            }
        }
        // 关闭 Archive 对象
        archive.close();
    }

测试

    public static void main(String[] args) throws RarException, IOException {

        unRar("F:\\tmp\\1\\压缩包.rar", "F:\\tmp\\1\\unrar");
    }
Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐