import lombok.extern.slf4j.Slf4j;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* @description: rar解压, 调用winrar.exe
* @author: wujie
* @create: 2020-07-21 10:03
**/
@Slf4j
public class UnRar5Utils {
//系统安装的winRAR位置
private static final String WINRAR_PATH = "C:\\Program Files\\WinRAR\\WinRAR.exe";
/**
* windows 解压方法
* @param rarFilePath rar压缩文件路径
* @param unFilePath 指定解压路径
* @throws IOException
* @throws InterruptedException
*/
public static void unRARFileWindows(String rarFilePath, String unFilePath) throws IOException, InterruptedException {
File file = new File(unFilePath);
if (!file.exists()) {
file.mkdirs();
}
String cmd = WINRAR_PATH + " x -r -o+ -ibck -y " + rarFilePath + " " + unFilePath;
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(cmd);
InputStreamReader isr = new InputStreamReader(process.getInputStream(), "gbk");
BufferedReader br = new BufferedReader(isr);
br.close();
//等待cmd 命令执行完成
process.waitFor();
}
/**
* 采用命令行方式解压文件 Linux
* <p>
* linux中安装unrar
* (1)上传unrar到linux服务器
* 如 /usr 路径
* (2)解压到指定路径:
* tar -zxf /usr/rarlinux-x64-5.7.1.tar.gz -C /usr/local/
* (3)建立软连接:必须要有软连接,类似于jdk的环境变量,保证可以在任意目录下使用rar和unrar命令
* ln -s /usr/local/rar/rar /usr/local/bin/rar
* ln -s /usr/local/rar/unrar /usr/local/bin/unrar
* (4)测试是否创建成功
* **在任意路径输入下列命令**
* rar
* unrar
* **出现如下信息表示安装成功**
* RAR 5.71 Copyright (c) 1993-2019 Alexander Roshal 28 Apr 2019
* Trial version Type 'rar -?' for help
*
* @param rarFilePath 压缩文件路径+文件名
* @param destDir 指定解压路径
* @return
*/
public static boolean unRARFileLinux(String rarFilePath, String destDir) throws Exception {
log.debug("begin unrar rarFilePath:{},destDir:{}", rarFilePath, destDir);
boolean bool = false;
File rarFile = new File(rarFilePath);
if (!rarFile.exists()) {
log.warn(":{} is not exist", rarFilePath);
return false;
}
File destDirPath = new File(destDir);
if (!destDirPath.exists()) {
destDirPath.mkdirs();
}
// 开始调用命令行解压,参数-o+是表示覆盖的意思
// String cmdPath = "/usr/local/bin/unrar"; 如果linux做了软连接 不需要这里配置路径
String cmd = "rar" + " X -o+ " + rarFile + " " + destDir;
log.debug("cmd :{}", cmd);
Process proc = Runtime.getRuntime().exec(cmd);
if (proc.waitFor() != 0) {
if (proc.exitValue() == 0) {
bool = false;
}
} else {
bool = true;
}
log.debug("unRar " + (bool ? "success" : "failed"));
return bool;
}
}