Java解压缩RAR文件
时间: 2023-09-22 17:07:33 浏览: 154
Java自带的解压缩库不支持RAR文件的解压缩,因此需要使用第三方库来实现。其中,比较常用的有两个库:junrar和SevenZipJBinding。
使用junrar库来解压缩RAR文件的示例代码如下:
1. 添加依赖
```
<dependency>
<groupId>com.github.junrar</groupId>
<artifactId>junrar</artifactId>
<version>1.0.0</version>
</dependency>
```
2. 编写解压缩代码
```
import com.github.junrar.Archive;
import com.github.junrar.rarfile.FileHeader;
import java.io.File;
import java.io.FileOutputStream;
public class RarExtractor {
public static void extract(String archivePath, String destinationPath) throws Exception {
Archive archive = new Archive(new File(archivePath));
FileHeader fileHeader = archive.nextFileHeader();
while (fileHeader != null) {
String fileName = fileHeader.getFileNameW().isEmpty() ? fileHeader.getFileNameString() : fileHeader.getFileNameW();
String filePath = destinationPath + File.separator + fileName;
if (fileHeader.isDirectory()) {
new File(filePath).mkdirs();
} else {
FileOutputStream fos = new FileOutputStream(new File(filePath));
archive.extractFile(fileHeader, fos);
fos.close();
}
fileHeader = archive.nextFileHeader();
}
archive.close();
}
public static void main(String[] args) throws Exception {
String archivePath = "/path/to/archive.rar";
String destinationPath = "/path/to/destination";
extract(archivePath, destinationPath);
}
}
```
使用SevenZipJBinding库来解压缩RAR文件的示例代码如下:
1. 添加依赖
```
<dependency>
<groupId>net.sf.sevenzipjbinding</groupId>
<artifactId>sevenzipjbinding</artifactId>
<version>9.20-2.00</version>
</dependency>
```
2. 编写解压缩代码
```
import net.sf.sevenzipjbinding.*;
import net.sf.sevenzipjbinding.impl.RandomAccessFileInStream;
import net.sf.sevenzipjbinding.simple.ISimpleInArchive;
import net.sf.sevenzipjbinding.simple.ISimpleInArchiveItem;
import java.io.File;
import java.io.FileOutputStream;
public class RarExtractor {
public static void extract(String archivePath, String destinationPath) throws Exception {
RandomAccessFileInStream inputStream = new RandomAccessFileInStream(new File(archivePath));
IInArchive archive = SevenZip.openInArchive(null, inputStream);
ISimpleInArchive simpleInArchive = archive.getSimpleInterface();
for (ISimpleInArchiveItem item : simpleInArchive.getArchiveItems()) {
String filePath = destinationPath + File.separator + item.getPath();
if (item.isFolder()) {
new File(filePath).mkdirs();
} else {
FileOutputStream fos = new FileOutputStream(new File(filePath));
byte[] buffer = new byte[4096];
item.extractSlow(new ISequentialOutStream() {
@Override
public int write(byte[] data) throws SevenZipException {
try {
fos.write(data);
} catch (Exception e) {
throw new SevenZipException(e);
}
return data.length;
}
});
fos.close();
}
}
archive.close();
inputStream.close();
}
public static void main(String[] args) throws Exception {
String archivePath = "/path/to/archive.rar";
String destinationPath = "/path/to/destination";
extract(archivePath, destinationPath);
}
}
```
阅读全文