一Java 解压rar文件
1.1 引入pom依赖
<dependency>
<groupId>com.github.junrar</groupId>
<artifactId>junrar</artifactId>
<version>4.0.0</version>
</dependency>
1.2 解压代码
// 加载rar文件
Archive archive = new Archive(new File("/home/a.rar"));
List<FileHeader> fileHeaders = archive.getFileHeaders();
if (fileHeaders == null) {
throw new BizException("压缩文件中不存在文件");
}
// 解压第一个文件
FileHeader fileHeader = fileHeaders.get(0);
OutputStream outputStream = null;
try {
outputStream = new FileOutputStream();
// 将解压的文件放入outputStream
archive.extractFile(fileHeader, outputStream);
// 伪代码:写入磁盘
write(outputStream)
}catch (Exception e) {
throw e;
}finally {
if (outputStream != null) {
outputStream.close();
}
}
二、解压zip
2.1 引入pom依赖
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>1.18</version>
</dependency>
2.2 代码
2.3 加载内存中的zip文件
//bytes表示内存中zip文件
SeekableInMemoryByteChannel inMemoryByteChannel = new SeekableInMemoryByteChannel(bytes);
ZipFile zipFile = new ZipFile(inMemoryByteChannel);
// 判断zip中是否还有剩余的文件
while (zipFile.getEntries().hasMoreElements()) {
//提取文件
ZipArchiveEntry zipArchiveEntry = zipFile.getEntries().nextElement();
//获取输入流
InputStream zipFileInputStream = zipFile.getInputStream(zipArchiveEntry);
FileOutputStream outputStream = new FileOutputStream();
IOUtils.copy(zipFileInputStream, outputStream);
//伪代码:写入磁盘
write(outputStream);
outputStream.close();
2.4 加载磁盘中的zip文件
ZipFile zipFile = new ZipFile(new File("/home/a.zip"));
//剩余步骤与2.3一致
...
参考文档:https://commons.apache.org/proper/commons-compress/examples.html