最近java语言项目集成7zip解压文件夹,后端下载了一个经特殊算法压缩的 zip 文件,由于不能用 java 本身自带的解压方式,必须採用 7Zip 来解压。因此,提到了本文中在 java后端调用外部 7zip exe 来解压文件,以解决此问题,实现过程如下:
1、定义缓冲区类
package com.roy.config;
import java.io.*;
import java.nio.charset.Charset;
/**
* 解压文件
*/
public class CommonStreamGobbler extends Thread{
InputStream is;
String type;
public CommonStreamGobbler(InputStream is, String type) {
this.is = is;
this.type = type;
}
public void run() {
try {
InputStreamReader isr = new InputStreamReader(is, Charset.forName("GBK"));
BufferedReader br = new BufferedReader(isr);
String line=null;
while ((line = br.readLine()) != null) {
System.out.println(type + ">" + line);
}
} catch (IOException ioe){
ioe.printStackTrace();
}
}
}
2、下载 7z.exe 过程
选择合适的版本下载
3、运行外部 7z.exe流程
/**
* cmd 7z 解压
* @param outPutFile
* @param outputDir
* @return
* @throws InterruptedException
*/
public static int unzip (String outPutFile,String outputDir,String zipToPackagePath) throws InterruptedException, IOException {
String[] cmd = {
// "C:\\Program Files\\7-Zip\\7z.exe",
zipToPackagePath,//7-Zip安装的路径
"x",//x:完整路径下解压文件
"-y",//-y:所有确认选项都默认为是(即不出现确认提示)
"-aos", // 跳过已存在的文件
outPutFile,//D:\test\测试文件.zip"-x!*MSS*",
"-o" + outputDir//-o:设置输出目录,D:\test
};
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(cmd);
// 监听出错信息
CommonStreamGobbler errorGobbler = new CommonStreamGobbler(proc.getErrorStream(), "ERROR");
// 监听输出信息
CommonStreamGobbler outputGobbler = new CommonStreamGobbler(proc.getInputStream(), "OUTPUT");
// 启动监听输入
errorGobbler.start();
outputGobbler.start();
// 确保 Runtime.exec 进程运行完成
int exitVal = proc.waitFor();
System.out.println("ExitValue: " + exitVal);
return exitVal;
}
4、调用7-Zip压缩.zip文件
/**
* 生成.toZip压缩文件
* @param filePath 需要压缩的文件路径
* @param zipFileName 生成压缩文件的文件名(全路径)
* @throws Exception
*/
public static void fileToZip(String filePath, String zipFileName) throws Exception {
//zipToolPath 是本地7-Zip软件的安装路径
String zipToolPath = "C:/Program Files/7-Zip/7z.exe";
zipToolPath = zipToolPath .replaceAll(" ", "\" \"");//所有空格都替换成带有双引号的空格
String exec = zipToolPath + " a " + zipFileName + " -r *.*";
File file = new File(filePath);
Runtime.getRuntime().exec(exec,null,file);
//执行成功后在ZipFileName路径下可以找到相应的压缩文件
}
集成过程中可能遇到一些问题,可以参考这篇文章,感觉总结的比较全面
到此、外部解压和压缩分享完毕,小伙伴手动演示一次,就会很快掌握。