Java Runtime.getRuntime()。exec无法捕获所有输出

时间:2019-06-13 17:05:09

标签: java

我的shell脚本 run.sh

echo "Running my.r"
Rscript /opt/myproject/my.r

从命令行输出 run.sh

Running my.r
2019-06-14 job starts at 2019-06-13 16:52:21
========================================================================
1. Load parameters from csv files.
Error in file(file, "rt") : cannot open the connection
Calls: automation.engine ... %>% -> eval -> eval -> read.csv -> read.table -> file
In addition: Warning message:
In file(file, "rt") :
  cannot open file '/...../_nodes.csv': No such file or directory

但是,我的Java程序只能捕获第一行“ Running my.r”。如何捕获输出的每一行?下面是我的Java代码:

Process proc = Runtime.getRuntime().exec("/opt/myproject/run.sh");
            BufferedReader read = new BufferedReader(new InputStreamReader(
                    proc.getInputStream()));
            try {
                proc.waitFor();
            } catch (InterruptedException e) {
                e.printStackTrace();
                throw e;
            }
            while (read.ready()) {
                String line = new String(read.readLine());
                results += "\r\n" + line;
                System.out.println(line);
            }

1 个答案:

答案 0 :(得分:3)

这是因为您仅从Process#getInputStream(如System.out)捕获标准输出,并且错误以错误流(System.err)打印。您还必须捕获Process#getErrorStream()

您可以使用Runtime.exec()代替ProcessBuilder,然后在其上调用redirectErrorStream来合并这两个流。

https://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html#redirectErrorStream()