记录下引入maven的相关坐标后,在archivers包下没有找到rar包
import org.apache.commons.compress.archivers.rar.RarArchiveEntry;
Java本身不提供解压RAR压缩包的功能,需要借助第三方库来实现。以下是使用Apache Commons Compress库来解压RAR压缩包的示例代码:
import org.apache.commons.compress.archivers.ArchiveEntry;import org.apache.commons.compress.archivers.ArchiveException;import org.apache.commons.compress.archivers.ArchiveInputStream;import org.apache.commons.compress.archivers.ArchiveStreamFactory;import org.apache.commons.compress.archivers.rar.RarArchiveEntry;import org.apache.commons.compress.archivers.rar.RarArchiveInputStream;import org.apache.commons.io.IOUtils;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;public class RarExtractor { public static void extract(String rarFile, String destDir) throws IOException, ArchiveException { File destinationDir = new File(destDir); if (!destinationDir.exists()) { destinationDir.mkdirs(); } try (ArchiveInputStream in = new ArchiveStreamFactory() .createArchiveInputStream(ArchiveStreamFactory.RAR, new FileInputStream(rarFile))) { RarArchiveInputStream rarIn = (RarArchiveInputStream) in; RarArchiveEntry entry; while ((entry = (RarArchiveEntry) rarIn.getNextEntry()) != null) { if (entry.isDirectory()) { new File(destinationDir, entry.getName()).mkdirs(); } else { File outputFile = new File(destinationDir, entry.getName()); FileOutputStream out = new FileOutputStream(outputFile); IOUtils.copy(rarIn, out); out.close(); } } } } public static void main(String[] args) throws IOException, ArchiveException { String rarFile = "path/to/your/rar/file.rar"; String destDir = "path/to/your/destination/directory"; extract(rarFile, destDir); }}
这个示例代码通过解析RAR文件的文件头来提取压缩包中的文件。在解压过程中,他们将提取的内容写入到目标目录中的新文件中。要使用此示例代码,你需要先将Apache Commons Compress库添加到你的Java项目的类路径中。
来源地址:https://blog.csdn.net/qq_34412985/article/details/131449127