java - 使用 Apache Commons Exec 时如何分别收集标准输出和标准错误?

标签 java stdout stderr apache-commons-exec

以下代码获取所有输出,无论是 stdout 还是 stderr。

String line = String.format("paty/to/script.py");
CommandLine cmd = CommandLine.parse(line);
DefaultExecutor executor = new DefaultExecutor();
ByteArrayOutputStream stdout = new ByteArrayOutputStream();
PumpStreamHandler psh = new PumpStreamHandler(stdout);
executor.setStreamHandler(psh);
int exitvalue = executor.execute(cmd);
String output = stdout.toString();

如何分别获取两个流?

最佳答案

PumpStreamHandler 为 stderr 采用第二个构造函数参数。如您所见,只有一个 OutputStream 的构造函数将同时写入 stdout 和 stderr。
https://commons.apache.org/proper/commons-exec/apidocs/org/apache/commons/exec/PumpStreamHandler.html

所以下面的方法应该可以处理它。

    String line = String.format("paty/to/script.py");
    CommandLine cmd = CommandLine.parse(line);
    DefaultExecutor executor = new DefaultExecutor();
    ByteArrayOutputStream stdout = new ByteArrayOutputStream();
    ByteArrayOutputStream stderr = new ByteArrayOutputStream();
    PumpStreamHandler psh = new PumpStreamHandler(stdout, stderr);
    executor.setStreamHandler(psh);
    int exitvalue = executor.execute(cmd);
    String output = stdout.toString();
    String error = stderr.toString();

关于java - 使用 Apache Commons Exec 时如何分别收集标准输出和标准错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34571340/

相关文章:

powershell - 将 'standard error' 更改为 'standard output'

使用 Java 运行项目时出现 java.lang.NoClassDefFoundError,但使用 mvn exec :exec 运行时有效

java - oracle sql - 在我的数据库表的一列中存储 4000 个字符

c# - 使用 Process.kill 异常终止进程后读取 StdOut

python - Paramiko 服务器 : Signalling the client that stdout is closed

python - 如何捕获长时间运行的程序的输出并将其呈现在 Python 的 GUI 中?

java - JPanel GridLayout 不添加组件

java - 无法从 WAS Liberty 服务器中部署的 Spring boot 应用程序访问 JNDI Url 上下文

c++ - 将更多输出订阅到 QTextStream

linux - Shell - 将 stderr 传递给第二个 shell 脚本并使用它