package com.iailab.module.model.mpk.common.utils; import com.iailab.module.model.mpk.common.MdkConstant; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; @Slf4j public class CmdUtils { public static void exec(String cmd, String directory) { Process process = null; BufferedReader normalReader = null; BufferedReader errorReader = null; try { log.info("执行cmd命令:" + cmd); ProcessBuilder builder = new ProcessBuilder("cmd", "/c", cmd); if (StringUtils.isNotBlank(directory)) { builder.directory(new File(directory)); } process = builder.start(); normalReader = new BufferedReader(new InputStreamReader(process.getInputStream(),"GBK")); errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream(),"GBK")); String line = null; while ((line = normalReader.readLine()) != null) { log.info("脚本文件执行信息normalStream:{}", line); } String errorLine; while ((errorLine = errorReader.readLine()) != null) { log.warn("脚本文件执行信息ErrorStream:{}", errorLine); } process.waitFor(); } catch (Exception e) { throw new RuntimeException("执行cmd命令异常,【" + cmd + "】",e); } finally { if (null != normalReader) { try { normalReader.close(); } catch (IOException e) { log.error("流文件关闭异常:", e); } } if (null != errorReader) { try { errorReader.close(); } catch (IOException e) { log.error("流文件关闭异常:", e); } } if (null != process) { process.destroy(); } } } public static void exec(String cmd) { exec(cmd,null); } }