import com.github.junrar.Archive;
import com.github.junrar.exception.RarException;
import com.github.junrar.rarfile.FileHeader;
import org.apache.commons.compress.archivers.ArchiveException;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
import java.io.*;
public class DecompressionUtil {
/**
*
* @param filePath 压缩包路径
* @param destDirectory 解压后的文件所在目录
*/
public static void decompression(String filePath, String destDirectory){
File destDir = new File(destDirectory);
if (!destDir.exists()) {
destDir.mkdir();
}
try{
if(filePath.endsWith("zip")){
unzip(filePath,destDirectory);
}else if(filePath.endsWith("rar")){
unrar(filePath,destDirectory);
}else {
System.out.println("暂时不持支该格式的压缩包");
}
}catch (Exception e){
e.printStackTrace();
}
}
private static void unzip(String zipFilePath, String destDirectory) throws IOException {
try (ZipArchiveInputStream zipInputStream = new ZipArchiveInputStream(new FileInputStream(zipFilePath))) {
ZipArchiveEntry entry;
while ((entry = zipInputStream.getNextZipEntry()) != null) {
String filePath = destDirectory + File.separator + entry.getName();
if (!entry.isDirectory()) {
extractFile(zipInputStream, filePath);
} else {
new File(filePath).mkdir();
}
}
}
}
private static void unrar(String rarFilePath, String destDirectory) throws IOException, ArchiveException {
try {
Archive archive = new Archive(new File(rarFilePath));
// 遍历RAR文件中的项
FileHeader fileHeader;
while ((fileHeader = archive.nextFileHeader()) != null) {
// 构建解压缩的目标文件路径
String destFilePath = destDirectory+ fileHeader.getFileName();
if(fileHeader.getFileName()==null||"".equals(fileHeader.getFileName())){
continue;
}
// 创建解压缩的目标文件
File destFile = new File(destFilePath);
if(destFile.exists()){
continue;
}
destFile.getParentFile().mkdirs();
// 解压缩RAR文件中的项
try (FileOutputStream fos = new FileOutputStream(destFile)) {
archive.extractFile(fileHeader, fos);
}
}
} catch (IOException | RarException e) {
e.printStackTrace();
}
System.out.println("解压缩完成!");
}
private static void extractFile(InputStream inputStream, String filePath) throws IOException {
try (FileOutputStream fos = new FileOutputStream(filePath)) {
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
fos.write(buffer, 0, length);
}
}
}
}
核心依赖:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>1.18</version>
</dependency>
<dependency>
<groupId>com.github.junrar</groupId>
<artifactId>junrar</artifactId>
<version>7.5.5</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-nop</artifactId>
<version>1.7.2</version>
</dependency>
WinRAR默认的压缩方式是rar5,上述代码中的解压rar只能解压rar4。