你需要兩個線程捕獲standal輸出或錯誤輸出是這樣的:
package demo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ExecDemo {
public static void main(String[] args) throws Exception {
final Process p = Runtime.getRuntime().exec("nslookup google.com");
Thread stdout = new Thread() {
public void run() {
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
try {
while ((line = br.readLine())!=null) {
System.out.println(line);
}
br.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
};
Thread stderr = new Thread() {
public void run() {
BufferedReader br = new BufferedReader(new InputStreamReader(p.getErrorStream()));
String line = null;
try {
while ((line = br.readLine())!=null) {
System.out.println(line);
}
br.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
};
//
stdout.start();
stderr.start();
//
stdout.join();
stderr.join();
//
p.waitFor();
}
}
輸出(在Mac OS X):
Server: 192.168.6.1
Address: 192.168.6.1#53
Non-authoritative answer:
Name: google.com
Address: 74.125.31.113
Name: google.com
Address: 74.125.31.138
Name: google.com
Address: 74.125.31.139
Name: google.com
Address: 74.125.31.100
Name: google.com
Address: 74.125.31.101
Name: google.com
Address: 74.125.31.102
「它不工作」 是*永不*足夠的信息。與你預期發生的事情相比,發生了什麼?請閱讀http://tinyurl.com/so-list – 2013-02-24 09:55:10
你是否從shell或CLI執行了這個命令,看看它是否真的用於Java? – asgs 2013-02-24 10:00:04
其實我想發短信到與我的電腦連接的電腦上使用Lan。我正在使用IP Messenger工具。我想通過java程序來運行這個工具,因此我輸入命令 「ipmsg.exe/MSG ipaddress text_message」。但是,當我使用java程序時,此命令不起作用 – user2087814 2013-02-24 10:02:55