java使用org.apache.commons:commons-compress解压 .7z压缩包
前言
java使用org.apache.commons:commons-compress解压 .7z压缩包
一、使用步骤
1.引入库
代码如下(示例):cpmpress需要用到xz依赖,不一起引入会报错。
<!-- https://mvnrepository.com/artifact/org.tukaani/xz -->
<dependency><groupId>org.tukaani</groupId><artifactId>xz</artifactId><version>1.9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-compress -->
<dependency><groupId>org.apache.commons</groupId><artifactId>commons-compress</artifactId><version>1.21</version>
</dependency>
2.解压代码实例
/*** 解压缩 .7z 格式的压缩包。** @param filePath 压缩包文件绝对路径。*/public viod SevenZCompress(String filePath) {/*逻辑:1. 解压 .7z 文件。2. 遍历压缩包中的每个文件。2.1. 过滤 MAC 压缩出来的多余文件夹。2.3. 获取原始文件名, 拼接要保存的目标文件路径。2.4. 保存文件。*/// [1] 解压 .7z 文件。try (SevenZFile sevenZFile = new SevenZFile(new File(filePath))) {// [2] 遍历压缩包中的每个文件。SevenZArchiveEntry entry;while ((entry = sevenZFile.getNextEntry()) != null) {// [2.1] 只解压文件, 跳过文件夹+过滤 MAC 压缩出来的多余文件夹。if (!entry.isDirectory() && !StringUtils.startsWithIgnoreCase(entry.getName(), "__MACOSX")) {// [2.2] 获取原始文件名, 拼接要保存的目标文件路径。String originalFileName = entry.getName();String fileUid = super.nextId() + "";String outFilePath = "D:/" + entry.getName();// [2.3] 保存文件。File outFile = new File(outFilePath);File parent = outFile.getParentFile();if (!parent.exists()) {FileUtil.mkdir(parent);}// 获取到当前文件的输入流, 写出到目标文件即可。try (InputStream inputStream = sevenZFile.getInputStream(entry)) {// 这里使用了org.apache.commons.io 包下的 FileUtils 工具类FileUtils.copyInputStreamToFile(inputStream, outFile);}}}} catch (Exception e) {throw new RuntimeException("解压 .7z 文件异常: "+ Utils.truncateExceptionMessage(e));}}
3.附 FileUtils的依赖
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.16.1</version>
</dependency>