Runtime.getRuntime().exec(“C:\cygwin\bin\bash.exe”) has no input to read

前端 未结 2 1249
悲哀的现实
悲哀的现实 2021-01-14 23:08

I\'m trying to execute a new process and read from its input stream in Java. I have successfully used Runtime.getRuntime().exec(String) to start and receive input from sever

2条回答
  •  感情败类
    2021-01-14 23:51

    A process typically has not only one but two output streams associated with it. These are:

    1. stdout, which can be read with getInputStream()
    2. stderr, which can be read with getErrorStream()

    Javac writes to stderr, not stdout, so you don't read its output.

    Because it is inconvenient to have to read both of them (Some years ago, I had to write an extra thread for this), they introduced a new API to system processes, namely the ProcessBuilder, which allows to redirect stderr to stdout.

    Just replace the lines

        Process proc = Runtime.getRuntime().exec(command);
        InputStream in = proc.getInputStream();
    

    with

        ProcessBuilder pb = new ProcessBuilder(command);
        pb.redirectErrorStream(true);
        Process proc = pb.start();
    

    , add the required imports, and your test succeeds :).

提交回复
热议问题