将stdout复制到java prcesses之间的stdin

时间:2018-03-08 13:10:00

标签: java process

我尝试将一个进程的stdout复制到stdin到两个新进程。但不知何故,这不能按预期工作,并且令人惊讶地难以调试。我在这里缺少什么?

public class Foo {
    public static void main(String[] args) throws Exception {
        Process pA = new ProcessBuilder("java", "-version").start();
        Process pB = new ProcessBuilder("bash", "-c", "cat").start();

        InputStream stdErrA = pA.getErrorStream();
        OutputStream stdInB = pB.getOutputStream();
        ByteArrayOutputStream cmdInB2 = new ByteArrayOutputStream();

        OutputStream tee = new TeeOutputStream(stdInB, cmdInB2);
        IOUtils.copy(stdErrA, tee);
        pA.waitFor();
        stdInB.close(); // EDIT: results mostly in the expected behavior, but throws IOException broken pipe sometimes
        pB.waitFor();

        String resultOfBOut = IOUtils.toString(pB.getInputStream(), "UTF-8");
        String copyOfAOut = cmdInB2.toString("UTF-8");
    }
}

0 个答案:

没有答案