背景:线上Linux服务器使用TarArchiveInputStream解压太慢
/**
*
* @param filePath 文件全路径
* @param extractPath 解压路径
* @return
*/
public static Boolean extractFile(String filePath, String extractPath){
File sourceFile = new File(filePath);
if (!sourceFile.exists()) {
logger.info("file not exist! {}------", filePath);
return false;
}
File extractFolder = new File(extractPath);
if (!extractFolder.exists()) {
//创建文件夹
extractFolder.mkdirs();
}
//执行解压命令解压tar
Runtime run = Runtime.getRuntime();
Process process = null;
logger.info("extractFile start: {}------", filePath);
try {
//在单独的进程中执行指定的外部可执行程序的启动路径或字符串命令
String cmd = "tar -zxvf " + sourceFile + " -C " + extractPath;
logger.info("extractFile command:[{}] ", cmd);
process = run.exec(cmd);
//处理子进程的输入流
new DealProcessStream(process.getInputStream()).start();
//处理子进程的错误流
new DealProcessStream(process.getErrorStream()).start();
// 阻塞当前线程,并等待外部程序结束
process.waitFor();
//释放子进程
process.destroy();
} catch (Exception e) {
logger.info("package File " + sourceFile + "untar failed");
return false;
}
logger.info("extractFile end: {}------", filePath);
//开发测试--------------------------------------
//Windows开发测试--------------------------START------------
// //解压
// TarArchiveInputStream fin = new TarArchiveInputStream(new FileInputStream(sourceFile));
// TarArchiveEntry entry;
// //将tar文件解压到extractpath目录下
// while ((entry = fin.getNextTarEntry()) != null) {
// logger.info("file :[{}] ", entry.getName());
// if (entry.isDirectory()) {
// continue;
// }
// File curFile = new File(extractFolder, entry.getName());
// IOUtils.copy(fin, new FileOutputStream(curFile));
// }
// logger.info("file extract finish!");
// //关流
// fin.close();
//Windows开发测试--------------------------END------------
return true;
}