Java代码调用cmd中的ping命令.如何获得ping返回的信息?

我在Java里执行cmd命令: Process p = Runtime.getRuntime().exec("ping -w " + timeout + " " + "www.usc.edu");
目的是Ping一下与"www.usc.edu"的连接情况
我在cmd里面测试是,问题是如何获得其中的信息,比如 Lost Average ???
求助!我Linux和C都不好,请教!

public static void main(String[] args) throws IOException, InterruptedException {

     // 执行ping命令

     String cmdPing = "ping 127.0.0.1";

     Runtime run = Runtime.getRuntime();

     Process process = run.exec(cmdPing);

     process.waitFor();

    BufferedReader br = new BufferedReader(new     InputStreamReader(process.getInputStream(), Charset.forName("GBK")));

    String line = null;

     while ((line = br.readLine()) != null) {

     System.out.println(line);

     }

}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-12-31
你应该看看api process 返回的是流,按照输出流的方法操作即可.公司上不去外网,有代理才行,所以没有ping 百度,ping的本机.

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

public class CallCmd {
public static void main(String[] args) {
BufferedReader br = null;
try {
Process p = Runtime.getRuntime().exec("ping 127.0.0.1");
br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
StringBuilder sb=new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
System.out.println(sb.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {

if (br != null) {
try {
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}本回答被提问者和网友采纳