dengzedong
8 天以前 f1fe397df175a7ee809ea28530419116af84af28
提交 | 用户 | 时间
011e9e 1 package com.iailab.module.model.mpk.common.utils;
D 2
3 import com.iailab.module.model.mpk.common.MdkConstant;
4 import lombok.extern.slf4j.Slf4j;
5 import org.apache.commons.lang3.StringUtils;
6
7 import java.io.BufferedReader;
8 import java.io.File;
9 import java.io.IOException;
10 import java.io.InputStreamReader;
11
12 @Slf4j
13 public class CmdUtils {
14
15     public static void exec(String cmd, String directory) {
16         Process process = null;
17         BufferedReader normalReader = null;
18         BufferedReader errorReader = null;
19         try {
20             log.info("执行cmd命令:" + cmd);
21             ProcessBuilder builder = new ProcessBuilder("cmd", "/c", cmd);
22             if (StringUtils.isNotBlank(directory)) {
23                 builder.directory(new File(directory));
24             }
25             process = builder.start();
26             normalReader = new BufferedReader(new InputStreamReader(process.getInputStream(),"GBK"));
27             errorReader = new  BufferedReader(new  InputStreamReader(process.getErrorStream(),"GBK"));
28
29             String line = null;
30             while ((line = normalReader.readLine()) != null) {
31                 log.info("脚本文件执行信息normalStream:{}", line);
32             }
33             String errorLine;
34             while ((errorLine = errorReader.readLine()) != null) {
35                 log.warn("脚本文件执行信息ErrorStream:{}", errorLine);
36             }
37             process.waitFor();
38         } catch (Exception e) {
39             throw new RuntimeException("执行cmd命令异常,【" + cmd + "】",e);
40         } finally {
41             if (null != normalReader) {
42                 try {
43                     normalReader.close();
44                 } catch (IOException e) {
45                     log.error("流文件关闭异常:", e);
46                 }
47             }
48             if (null != errorReader) {
49                 try {
50                     errorReader.close();
51                 } catch (IOException e) {
52                     log.error("流文件关闭异常:", e);
53                 }
54             }
55             if (null != process) {
56                 process.destroy();
57             }
58         }
59     }
60
61     public static void exec(String cmd) {
62         exec(cmd,null);
63     }
64 }