服务器之家

服务器之家 > 正文

Java 执行CMD命令或执行BAT批处理方式

时间:2021-11-11 13:34     来源/作者:它山之石,可以攻玉

Java 执行CMD命令或执行BAT批处理

背景

日常开发中总能遇到一些奇怪的需求,例如使用java执行cmd命令或者bat批处理文件,今天就简单记录一下使用过程。

使用

废话不多说直接上代码

?
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
public class Cmder {
    /**
     * 执行一个cmd命令
     *
     * @param cmdCommand cmd命令
     * @return 命令执行结果字符串,如出现异常返回null
     */
    public static String executeCmdCommand(String cmdCommand) {
        StringBuilder stringBuilder = new StringBuilder();
        Process process = null;
        try {
            process = Runtime.getRuntime().exec(cmdCommand);
            BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(process.getInputStream(), "GBK"));
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line).append(" ");
            }
            return stringBuilder.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    /**
     * 执行bat文件,
     *
     * @param file          bat文件路径
     * @param isCloseWindow 执行完毕后是否关闭cmd窗口
     * @return bat文件输出log
     */
    public static String executeBatFile(String file, boolean isCloseWindow) {
        String cmdCommand = null;
        if (isCloseWindow) {
            cmdCommand = "cmd.exe /c " + file;
        } else {
            cmdCommand = "cmd.exe /k " + file;
        }
        StringBuilder stringBuilder = new StringBuilder();
        Process process = null;
        try {
            process = Runtime.getRuntime().exec(cmdCommand);
            BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(process.getInputStream(), "GBK"));
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line).append(" ");
            }
            return stringBuilder.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    /**
     * 执行bat文件,新开窗口
     *
     * @param file          bat文件路径
     * @param isCloseWindow 执行完毕后是否关闭cmd窗口
     * @return bat文件输出log
     */
    public static String executeBatFileWithNewWindow(String file, boolean isCloseWindow) {
        String cmdCommand;
        if (isCloseWindow) {
            cmdCommand = "cmd.exe /c start" + file;
        } else {
            cmdCommand = "cmd.exe /k start" + file;
        }
        StringBuilder stringBuilder = new StringBuilder();
        Process process;
        try {
            process = Runtime.getRuntime().exec(cmdCommand);
            BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(process.getInputStream(), "GBK"));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line).append(" ");
            }
            return stringBuilder.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    /**
     * 执行bat脚本
     *
     * @param batScript 脚本内容
     * @param location  脚本存储路径
     * @return 结果
     */
    public static String executeBatScript(String batScript, String location) {
        StringBuilder stringBuilder = new StringBuilder();
        FileWriter fw = null;
        try {
            //生成bat文件
            fw = new FileWriter(location);
            fw.write(batScript);
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Process process;
        try {
            process = Runtime.getRuntime().exec(location);
            BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(process.getInputStream(), "GBK"));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line).append(" ");
            }
            return stringBuilder.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    /**
     * 执行脚本,不停止,并输出执行结果
     *
     * @param batScript 脚本内容
     * @param location  bat文件生成地址
     */
    public void executeBatScriptAlways(String batScript, String location) {
        FileWriter fw = null;
        try {
            //生成bat文件
            fw = new FileWriter(location);
            fw.write(batScript);
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        StringBuilder stringBuilder = new StringBuilder();
        //运行bat文件
        Process process;
        try {
            process = Runtime.getRuntime().exec(location);
            BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(process.getInputStream(), "GBK"));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Java 执行系统命令

1. windows

1.1 cmd

第一种方法

?
1
2
3
4
5
6
7
8
9
10
11
12
File dir = new File("D:\mysql57\mysql-5.7.29-winx64\bin");
// String command="netstat -an";
String command = "c:\windows\system32\cmd.exe /c mysqlbinlog  ../data/master-bin.000006 | more";
Runtime r = Runtime.getRuntime();
Process p = r.exec(command, null, dir);
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
StringBuffer sb = new StringBuffer();
String inline;
while (null != (inline = br.readLine())) {
    sb.append(inline).append(" ");
}
System.out.println(sb.toString());

第二种方法

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
try {
    File dir = new File("D:\mysql57\mysql-5.7.29-winx64\bin");//此处是指定路径
    String[] cmd = new String[] { "cmd", "/c",
            "mysqlbinlog -v ../data/master-bin.000006 | more"
    };// cmd[2]是要执行的dos命令
    System.out.println(cmd[2]);
    Process process = Runtime.getRuntime().exec(cmd,null,dir);
    // 记录dos命令的返回信息
    StringBuffer resStr = new StringBuffer();
    // 获取返回信息的流
    InputStream in = process.getInputStream();
    Reader reader = new InputStreamReader(in);
    BufferedReader bReader = new BufferedReader(reader);
    for (String res = ""; (res = bReader.readLine()) != null;) {
        resStr.append(res + " ");
    }
    System.out.println(resStr.toString());
    bReader.close();
    reader.close();
    process.getOutputStream().close();  // 不要忘记了一定要关
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

windows cmd 命令

后台运行

?
1
2
start /b 程序名字
start /b redis-server.exe redis.windows.conf

Java 执行CMD命令或执行BAT批处理方式

关闭程序

?
1
2
taskkill /f /t /im 程序名字
taskkill /f /t /im redis-server.exe

Java 执行CMD命令或执行BAT批处理方式

查看进程

根据进程名称 查看进程

?
1
tasklist|find /i "redis-server.exe"

以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/y534560449/article/details/116232595

标签:

相关文章

热门资讯

yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
2021年耽改剧名单 2021要播出的59部耽改剧列表
2021年耽改剧名单 2021要播出的59部耽改剧列表 2021-03-05
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
返回顶部