命令输出中文编码
String line=”ping “;
CommandLine cmdLine=CommandLine.parse(line);
cmdLine.addArgument(“www.baidu.com”);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ByteArrayOutputStream errorStream = new ByteArrayOutputStream();
PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream,errorStream);
DefaultExecutor executor=new DefaultExecutor();
executor.setStreamHandler(streamHandler);
int exitValue=executor.execute(cmdLine);
String out =outputStream.toString(“gbk”);
String error =errorStream.toString(“gbk”);
System.out.println(exitValue);
System.out.println(out);
监视超时
//利用监视狗来设置超时
ExecuteWatchdogwatchdog = new ExecuteWatchdog(60000);
exec.setWatchdog(watchdog);
默认执行外部命令是阻塞式的,在执行命令时,当前线程是阻塞的。可以使用DefaultExecuteResultHandler处理外部命令执行的结果,释放当前线程。
DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
executor.execute(cmdLine, resultHandler);
//阻塞当前线程
resultHandler.waitFor();