在Java中,由于JDK自身并不直接支持RAR文件的解压,你需要使用第三方库,如SevenZipJAR或RarFile4j等。 以下是一个使用SevenZipJAR解压RAR文件的示例代码: ```java import net.sf.sevenzipjbinding.*; import net.sf.sevenzipjbinding.impl.*; import net.sf.sevenzipjbinding.util.*; import java.io.*; public class RarExtractor { public static void extract(String rarFilePath, String outputDirectory) throws Exception { SevenZipExtractor extractor = new SevenZipExtractor(rarFilePath); ExtractAskMode extractAskMode = ExtractAskMode.EXTRACT; for (ArchiveEntry entry : extractor.getArchiveEntries()) { File outputFilePath = new File(outputDirectory, entry.getPath()); if (entry.isDirectory()) { outputFilePath.mkdirs(); } else { outputFilePath.getParentFile().mkdirs(); OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFilePath)); extractor.extract(entry, outputStream); outputStream.close(); } } extractor.close(); } public static void main(String[] args) throws Exception { extract("path_to_your.rar", "path_to_output_directory"); } } ``` 首先,你需要在项目中添加SevenZipJAR的依赖。如果你使用Maven,可以在pom.xml文件中添加如下依赖: ```xml <dependency> <groupId>net.sf.sevenzipjbinding</groupId> <artifactId>sevenzipjbinding</artifactId> <version>9.20-2</version> </dependency> <dependency> <groupId>net.sf.sevenzipjbinding</groupId> <artifactId>sevenzipjbinding-all-platforms</artifactId> <version>9.20-2</version> </dependency> ``` 上述代码需要SevenZipJAR提供的动态库文件(dll或so)在系统的路径中或者与jar文件同目录下。 [2024-02-04 09:11:30 | AI写代码神器 | 412点数解答]