42
Commons exec提供了一個PumpStreamHandler,它將標準輸出重定向到Java進程的標準輸出。如何將命令的輸出捕獲到字符串中?如何以Commons Exec的字符串形式捕獲命令的輸出?
Commons exec提供了一個PumpStreamHandler,它將標準輸出重定向到Java進程的標準輸出。如何將命令的輸出捕獲到字符串中?如何以Commons Exec的字符串形式捕獲命令的輸出?
He're我發現了什麼:
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());
}
非常感謝你 – 2012-06-11 17:26:46