本例以Windows, JDK1.7 为基础,来演示Java 执行Command 命令。

在windows中我们可以使用cmd.exe来执行一些相关的命令,同样我们也可以使用java来调用系统的cmd.exe来执行命令。

例如使用Ping 命令:

在java中,通常使用Runtime.getRuntime().exec(?) 来执行命令:

实例代码:

1
2
3
4
5
6
7
8
Process process = Runtime.getRuntime().exec(cmd);

BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));

String line = "";
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line + "\r\n" );
}

Ping 命令演示

JavaExcuteCmd.java

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
package com.devnp.io;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class JavaExcuteCmd {

public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub

System.out.println(excuteCmd("ping www.devnp.com"));

System.out.println(excuteCmd("ping www.google.com"));
}

public static String excuteCmd(String cmd){
StringBuilder stringBuilder = new StringBuilder();

try {
Process process = Runtime.getRuntime().exec(cmd);

BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));

String line = "";
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line + "\r\n" );
}

bufferedReader.close();
} catch (IOException e) {
// TODO: handle exception

System.err.println(e);
}

return stringBuilder.toString() ;
}

}

运行结果:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Pinging ew-926om399.aliapp.com [121.199.250.*] with 32 bytes of data:
Reply from 121.199.250.*: bytes=32 time=200ms TTL=86
Reply from 121.199.250.*: bytes=32 time=223ms TTL=88
Reply from 121.199.250.*: bytes=32 time=213ms TTL=86
Reply from 121.199.250.*: bytes=32 time=195ms TTL=88

Ping statistics for 121.199.250.*:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 195ms, Maximum = 223ms, Average = 207ms


Pinging www.google.com [220.255.6.*] with 32 bytes of data:
Reply from 220.255.6.*: bytes=32 time=4ms TTL=59
Reply from 220.255.6.*: bytes=32 time=10ms TTL=59
Reply from 220.255.6.*: bytes=32 time=4ms TTL=59
Reply from 220.255.6.*: bytes=32 time=5ms TTL=59

Ping statistics for 220.255.6.*:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 4ms, Maximum = 10ms, Average = 5ms