String shell = "ping www.baidu.com";//需要执行的命令
BufferedReader br = null;
try {
Process p = Runtime.getRuntime().exec(shell);//调用控制台执行shell
br = new BufferedReader(new InputStreamReader(p.getErrorStream()));//获取执行后出现的错误;getInputStream是获取执行后的结果
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line + "
");
System.out.println(sb);
}
System.out.println(sb);//打印执行后的结果
} catch (Exception e) {
e.printStackTrace();
}
finally
{
if (br != null)
{
try {
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}