如何执行外部命令并捕获输出?

时间:2016-05-16 09:22:56

标签: java windows file cmd processbuilder

在java中,如何执行外部命令(如在Windows中的cmd或Linux中的terminal中),并在执行命令时捕获结果?

1 个答案:

答案 0 :(得分:1)

为此目的考虑Apache Commons Exec

It is a simple,但是实现多平台命令行调用的可靠框架。

以下是执行命令并将结果输出为String实例的示例方法。

import java.io.ByteArrayOutputStream;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.Executor;
import org.apache.commons.exec.PumpStreamHandler;

public String execToString(String command) throws Exception {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    CommandLine commandline = CommandLine.parse(command);
    DefaultExecutor exec = new DefaultExecutor();
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
    exec.setStreamHandler(streamHandler);
    exec.execute(commandline);
    return(outputStream.toString());
}
相关问题