Process output from apache-commons exec

后端 未结 4 1577
予麋鹿
予麋鹿 2020-12-10 10:11

I am at my wits end here. I\'m sure this is something simple and I most likely have huge holes in my understanding of java and streams. I think there are so many classes tha

4条回答
  •  隐瞒了意图╮
    2020-12-10 11:12

    Don't pass a ByteArrayOutputStream to the PumpStreamHandler, use an implementation of the abstract class org.apache.commons.exec.LogOutputStream. From the javadoc:

    The implementation parses the incoming data to construct a line and passes the complete line to an user-defined implementation.

    Thus the LogOutputStram is preprocessing the output to give you the control of handling individual lines instead of the raw bytes. Something like this:

    import java.util.LinkedList;
    import java.util.List;
    import org.apache.commons.exec.LogOutputStream;
    
    public class CollectingLogOutputStream extends LogOutputStream {
        private final List lines = new LinkedList();
        @Override protected void processLine(String line, int level) {
            lines.add(line);
        }   
        public List getLines() {
            return lines;
        }
    }
    

    Then after the blocking call to exec.execute your getLines() will have the standard out and standard error you are looking for. The ExecutionResultHandler is optional from the perspective of just executing the process, and collecting all the stdOut/stdErr into a list of lines.

提交回复
热议问题