Linux下解压.7z压缩包,java调用shell命令执行,解压速度是java程序解压的几十倍乃至更多,首先确认主机上已安装.7z命令。
package com.annet.upload.core.utils;import java.io.BufferedReader;import java.io.FileOutputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.io.OutputStreamWriter;import java.text.DateFormat;import java.text.SimpleDateFormat;import java.util.Date;import org.slf4j.Logger;import org.slf4j.LoggerFactory;/** * 执行shell解压命令 * * @author yanhu * @date 2017/12/11 */public class ShellUtils { // 基本路径 private static final String basePath = "/tmp/"; // 记录Shell执行状况的日志文件的位置(绝对路径) private static final String executeShellLogFile = basePath + "executeShell.log"; private static Logger logger = LoggerFactory.getLogger(ShellUtils.class); public static int executeShell(String shellCommand) throws Exception { int success = 0; StringBuffer stringBuffer = new StringBuffer(); BufferedReader bufferedReader = null; // 格式化日期时间,记录日志时使用 DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS "); try { stringBuffer.append(dateFormat.format(new Date())).append("准备执行Shell命令 ").append(shellCommand) .append("\r\n"); Process pid = null; String[] cmd = { "/bin/sh", "-c", shellCommand }; // 执行Shell命令 pid = Runtime.getRuntime().exec(cmd); if (pid != null) { stringBuffer.append("进程号:").append(pid.toString()).append("\r\n"); // bufferedReader用于读取Shell的输出内容 bufferedReader = new BufferedReader(new InputStreamReader(pid.getInputStream()), 1024); pid.waitFor(); } else { stringBuffer.append("没有pid\r\n"); } stringBuffer.append(dateFormat.format(new Date())).append("Shell命令执行完毕\r\n执行结果为:\r\n"); String line = null; // 读取Shell的输出内容,并添加到stringBuffer中 while (bufferedReader != null && (line = bufferedReader.readLine()) != null) { stringBuffer.append(line).append("\r\n"); } logger.info("解压完成"); } catch (Exception ioe) { logger.error("执行Shell命令时发生异常:" + ioe.getMessage()); stringBuffer.append("执行Shell命令时发生异常:\r\n").append(ioe.getMessage()).append("\r\n"); throw ioe; } finally { if (bufferedReader != null) { OutputStreamWriter outputStreamWriter = null; try { bufferedReader.close(); // 将Shell的执行情况输出到日志文件中 OutputStream outputStream = new FileOutputStream(executeShellLogFile); outputStreamWriter = new OutputStreamWriter(outputStream, "UTF-8"); outputStreamWriter.write(stringBuffer.toString()); } catch (Exception e) { e.printStackTrace(); } finally { outputStreamWriter.close(); } } success = 1; } return success; }}
try { long start = System.currentTimeMillis(); logger.info("开始解压:" + inputPath); //拼接shell解压命令 shellCode = "7za -p" + password + " x " + inputPath + " -r -o" + unzipPath; ShellUtils.executeShell(shellCode); logger.info("解压耗时:" + ((System.currentTimeMillis() - start) / 1000) + "S");} catch (Exception e) { e.printStackTrace(); return;}