开发者

How can I capture the output of a command as a String with Commons Exec?

开发者 https://www.devze.com 2023-03-12 06:29 出处:网络
Commons exec provides a PumpStreamHandler whi开发者_如何学编程ch redirects standard output to the Java process\' standard output. How can I capture the output of the command into a String?He\'re what

Commons exec provides a PumpStreamHandler whi开发者_如何学编程ch redirects standard output to the Java process' standard output. How can I capture the output of the command into a String?


He're what I found:

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

精彩评论

暂无评论...
验证码 换一张
取 消