潘志宝
2024-12-12 7324229be6b961411038fab3c680929ae05b0496
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
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);
    }
}