javastdoutstderrapache-commons-exec

How do I collect Standard Out and Standard Error separately when using Apache Commons Exec?


The below code gets all of the output, whether stdout or stderr.

String line = String.format("paty/to/script.py");
CommandLine cmd = CommandLine.parse(line);
DefaultExecutor executor = new DefaultExecutor();
ByteArrayOutputStream stdout = new ByteArrayOutputStream();
PumpStreamHandler psh = new PumpStreamHandler(stdout);
executor.setStreamHandler(psh);
int exitvalue = executor.execute(cmd);
String output = stdout.toString();

How can I get both streams separately?


Solution

  • PumpStreamHandler takes a second constructor argument for stderr. The constructor with only one OutputStream will have both stdout and stderr being written to it, as you observed.
    See https://commons.apache.org/proper/commons-exec/apidocs/org/apache/commons/exec/PumpStreamHandler.html

    So an approach as the following should handle it.

        String line = String.format("paty/to/script.py");
        CommandLine cmd = CommandLine.parse(line);
        DefaultExecutor executor = new DefaultExecutor();
        ByteArrayOutputStream stdout = new ByteArrayOutputStream();
        ByteArrayOutputStream stderr = new ByteArrayOutputStream();
        PumpStreamHandler psh = new PumpStreamHandler(stdout, stderr);
        executor.setStreamHandler(psh);
        int exitvalue = executor.execute(cmd);
        String output = stdout.toString();
        String error = stderr.toString();