引言
在开发过程中,我们经常需要处理压缩文件,如ZIP和RAR文件。本文将介绍如何使用Java解压这两种常见的压缩文件格式,具体包括使用java.util.zip
包解压ZIP文件和使用junrar
库解压RAR文件。
准备工作
在开始之前,请确保你已经准备好以下工具:
- Java开发环境(JDK 11或以上)
- 一个集成开发环境(IDE),例如IntelliJ IDEA或Eclipse
- Apache Commons IO库,用于处理文件操作
- junrar库,用于解压RAR文件
Maven依赖
如果你使用的是Maven项目,需要在pom.xml
文件中添加以下依赖:
<dependencies>
<!-- Apache Commons IO -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
<!-- junrar -->
<dependency>
<groupId>com.github.junrar</groupId>
<artifactId>junrar</artifactId>
<version>7.5.4</version>
</dependency>
</dependencies>
完整代码示例
以下是完整的Java代码示例,展示了如何解压RAR和ZIP文件。
package org.example;
import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Comparator;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import com.github.junrar.Archive;
import com.github.junrar.exception.RarException;
import com.github.junrar.rarfile.FileHeader;
import org.apache.commons.io.FileUtils;
import static java.lang.System.out;
public class Main {
public static void main(String[] args) {
// 压缩文件路径
String path = "C:\\Users\\BlaiseLin\\Desktop\\实验案例.rar";
// 根据文件扩展名选择解压方法
if (path.endsWith(".zip")) {
unzip(path);
} else if (path.endsWith(".rar")) {
unrar(path);
}
}
/**
* 初始化解压目录
*
* @param path 压缩文件路径
* @return 解压目录文件对象
*/
private static File init(String path) {
// 获取压缩文件对象和文件名
File file = new File(path);
String fileName = file.getName();
// 创建解压目录
File root = new File(file.getParent() + "\\" + fileName.substring(0, fileName.lastIndexOf(".")));
// 如果解压目录已存在,则删除
if (root.exists()) {
try {
FileUtils.deleteDirectory(root);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
// 创建新目录
root.mkdir();
return root;
}
/**
* 计算文件的MD5哈希值
*
* @param bytes 文件字节数组
* @return 哈希值字符串
* @throws NoSuchAlgorithmException 如果不支持MD5算法
*/
public static String hash(byte[] bytes) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(bytes);
return new String(md.digest());
}
/**
* 解压RAR文件
*
* @param path RAR文件路径
*/
private static void unrar(String path) {
out.println("解压rar文件");
File root = init(path);
try (Archive archive = new Archive(new FileInputStream(path))) {
// 获取所有文件头
List<FileHeader> fileHeaders = archive.getFileHeaders();
// 按文件名排序
fileHeaders.sort(Comparator.comparing(FileHeader::getFileName));
// 遍历文件头,解压每个文件或目录
for (FileHeader fileHeader : fileHeaders) {
out.println(fileHeader.getFileName());
File newFile = new File(root, fileHeader.getFileName());
if (fileHeader.isDirectory()) {
newFile.mkdir();
} else {
newFile.createNewFile();
// 写入文件内容
try (InputStream inputStream = archive.getInputStream(fileHeader)) {
FileUtils.copyInputStreamToFile(inputStream, newFile);
}
}
}
} catch (RarException | IOException e) {
throw new RuntimeException(e);
}
}
/**
* 解压ZIP文件
*
* @param path ZIP文件路径
*/
public static void unzip(String path) {
out.println("解压zip文件");
File file = new File(path);
File root = init(path);
try (ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(file))) {
ZipEntry zipEntry;
// 遍历ZIP文件中的每个条目
while ((zipEntry = zipInputStream.getNextEntry()) != null) {
out.println(zipEntry.getName());
File newFile = new File(root, zipEntry.getName());
if (zipEntry.isDirectory()) {
newFile.mkdir();
} else {
newFile.createNewFile();
// 写入文件内容
try (FileOutputStream fileOutputStream = new FileOutputStream(newFile)) {
byte[] bytes = new byte[1024];
int len;
while ((len = zipInputStream.read(bytes)) != -1) {
fileOutputStream.write(bytes, 0, len);
}
}
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
代码解析
主方法 (main
)
main
方法首先根据文件路径的扩展名判断要解压的文件类型,然后调用相应的解压方法。
初始化解压目录 (init
)
init
方法创建一个用于存放解压文件的目录。如果目录已经存在,则先删除它。
计算文件哈希值 (hash
)
hash
方法用于计算文件的MD5哈希值,这在某些需要校验文件完整性的场景中可能会用到。
解压RAR文件 (unrar
)
unrar
方法使用junrar
库来解压RAR文件。它首先初始化解压目录,然后遍历RAR文件中的所有文件头,根据文件头信息创建对应的文件或目录,并通过InputStream
将文件内容写入到新文件中。
解压ZIP文件 (unzip
)
unzip
方法使用java.util.zip
包来解压ZIP文件。它同样初始化解压目录,然后遍历ZIP文件中的所有条目,根据条目信息创建对应的文件或目录,并通过FileOutputStream
将文件内容写入到新文件中。