执行外部程序的Java类库:Apache Commons Exec 1.3 发布

jopen 10年前

Apache Commons Exec 1.3 发布了,Apache Commons Exec 是 Apache 上的一个 Java 项目,提供一些常用的方法用来执行外部进程。

改进记录包括:

新特性:
o DefaultExecutor async execute prevents shutdown hooks running.

Bug 修复:
o Remove remaining raw types, unchecked conversions
o NPE in EnvironmentUtils.toString(map)

改动:
o No need to use System.class.getMethod("getenv",...) any more
o Update JUnit dependency to 4.11
o Update to Java 5

利用Apache Commons Exec调用命令行并取得命令行的输出(实例)

    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();                        }                    }  

项目地址:http://commons.apache.org/proper/commons-exec/


来自:http://www.oschina.net/news/56823/apache-commons-exec-1-3