用Java如何解压rar文件格式

问题由来

在工作中遇到一个特殊需求需要解压rar文件,搜索了下很多文章,大致都类似AI的这个回答,如图:

已知解决方案

  1. 使用7z解压,在官网能下载到7z sdk
  2. 使用unrar命令行工具(这个需要先在服务器安装unrar),然后包装一个unrar工具类使用

解决方法(×)

  1. 使用commons-compress无法解压rar5.0版本的
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
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文件路径和输出目录路径。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值