利用Apache Commons Exec调用命令行并取得命令行的输出(实例)
http://blog.csdn.net/ligaoyang/article/details/8029020
|
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 |
Java代码 public String ping(String ip) { try { String command = "ping "+ip; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ByteArrayOutputStream errorStream = new ByteArrayOutputStream(); CommandLine commandline = CommandLine.parse(command); DefaultExecutor exec = new DefaultExecutor(); exec.setExitValues(null); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream,errorStream); exec.setStreamHandler(streamHandler); exec.execute(commandline); String out = outputStream.toString("gbk"); String error = errorStream.toString("gbk"); return out+error; } catch (Exception e) { log.error("ping task failed.",e); return e.toString(); } } |
