Java代码执行CMD命令

执行jps示例

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
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class EfferentProcess {
public static void main(String[] args) throws IOException, InterruptedException {
run("jps");
}


/**
* 执行cmd命令并获取输出结果
*/
public static void run(String cmd) {
Runtime runtime = Runtime.getRuntime();
try {
BufferedReader br = new BufferedReader(
new InputStreamReader(
runtime.exec(cmd).getInputStream(),
"GB2312"
)
);
String line;
StringBuilder b = new StringBuilder();
while ((line = br.readLine()) != null) {
b.append(line).append("\n");
}
System.out.println(b);
} catch (Exception e) {
e.printStackTrace();
}
}
}

参考

参考



----------- 本文结束 -----------




0%