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?
Asked
Active
Viewed 2.5k times
1 Answers
97
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());
}

Nicolas
- 2,321
- 4
- 21
- 32
-
1For a long-running task, I want to display the command line execution logs in real time on the front end. How should I collect real-time logs through OutputStream? – TimYi Apr 08 '22 at 21:23