java调用控制台命令

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 + "\n");
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();
}
}
}

posted @ 2016-09-02 09:55  ermei  阅读(4881)  评论(0编辑  收藏  举报