gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 19:38:19 25 4
gpt4 key购买 nike

我的 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);
}

最佳答案

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

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

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

关于Java Runtime.getRuntime().exec 无法捕获所有输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56585441/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com