package com.fdkankan.fusion.common.util; import lombok.extern.slf4j.Slf4j; import java.io.BufferedReader; import java.io.Closeable; import java.io.InputStreamReader; @Slf4j public class ShellUtil { /** * 执行系统命令, 返回执行结果 * @param cmd 需要执行的命令 */ public static void execCmd(String cmd) { StringBuilder result = new StringBuilder(); Process process = null; BufferedReader bufrIn = null; BufferedReader bufrError = null; long startTime = System.currentTimeMillis(); try { // 执行命令, 返回一个子进程对象(命令在子进程中执行) log.info("执行cmd:{}",cmd); process = Runtime.getRuntime().exec(cmd); // 方法阻塞, 等待命令执行完成(成功会返回0) process.waitFor(); // 获取命令执行结果, 有两个结果: 正常的输出 和 错误的输出(PS: 子进程的输出就是主进程的输入) bufrIn = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); bufrError = new BufferedReader(new InputStreamReader(process.getErrorStream(), "UTF-8")); // 读取输出 // String line = null; // while ((line = bufrIn.readLine()) != null) { // result.append(line).append('\n'); // } // while ((line = bufrError.readLine()) != null) { // result.append(line).append('\n'); // } }catch (Exception e){ e.printStackTrace(); }finally { closeStream(bufrIn); closeStream(bufrError); // 销毁子进程 if (process != null) { process.destroy(); } } // 返回执行结果 log.info("执行cmd:{},结果:{},耗时:{}", cmd,result.toString(),System.currentTimeMillis() -startTime); } private static void closeStream(Closeable stream) { if (stream != null) { try { stream.close(); } catch (Exception e) { e.printStackTrace(); } } } public static void unZip(String zipPath, String dataPath) { log.info("解压zip开始"); String command = "unzip -O GBK/GB18030CP936 " + zipPath + " -d " + dataPath; execCmd(command); log.info("解压zip完毕:" + command); } public static void unRar(String rarPath, String dataPath) { log.info("解压rar开始"); String command = "unrar e " + rarPath + " " + dataPath; execCmd(command); log.info("解压rar完毕:" + command); } }