Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

Commons exec provides a PumpStreamHandler which redirects standard output to the Java process' standard output. How can I capture the output of the command into a String?

like image 925
Nicolas Avatar asked Jun 09 '11 16:06

Nicolas


1 Answers

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());
}
like image 119
Nicolas Avatar answered Nov 20 '22 20:11

Nicolas