如何以Commons Exec的stringforms捕获命令的输出?

Commons exec提供了一个将标准输出redirect到Java进程标准输出的PumpStreamHandler。 如何捕获命令的输出到一个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()); }