【问题标题】:Incomplete output about Java Runtime.getRuntime().exec(command)关于 Java Runtime.getRuntime().exec(command) 的不完整输出
【发布时间】:2020-10-28 09:00:00
【问题描述】:

我想构建一个像 Jenkins 终端这样的应用程序:

而我用JavaRuntime.getRuntime().exec(command)执行命令,发现输出不全。

textshell.sh:

# textshell.sh
echo "wwwwwww";
sleep 2
ls

例如: 当我在我的 mac 终端sh -x testshell.sh 中执行 textshell.sh 时,输出:

+ echo wwwwwww
wwwwwww
+ sleep 2
+ ls
testshell.sh

但是当我通过 java Java Runtime.getRuntime().exec("sh -x testshell.sh") 执行时,输出:

wwwwwww
testshell.sh

shell args -x 似乎没用

我该如何解决?

【问题讨论】:

  • 似乎“+”前缀行被打印到 stderr。确保同时使用(并显示)标准输出和标准错误流。
  • 尝试运行这个Runtime.getRuntime().exec(new String[]{"sh", "-x", "testshell.sh"})
  • 阅读标准错误流并修复问题,非常感谢

标签: java terminal


【解决方案1】:

正如@Joachim Sauer 指出的那样,您没有阅读 STDERR,所以错过了来自 set -x 输出的 echo 输出行。调整您的代码以访问process.getErrorStream()

如果要读取与输出合并的错误流,您也可以切换到ProcessBuilder

String[]cmd = new String[]{"sh", "-x", "testshell.sh"}
ProcessBuilder pb = new ProcessBuilder(cmd);

// THIS MERGES STDERR>STDOUT:
pb.redirectErrorStream(true);

// EITHER send all output to a file here:
Path stdout = Path.of("mergedio.txt");
pb.redirectOutput(stdout.toFile());

Process p = pb.start();

// OR consume your STDOUT p.getInputStream() here as before:

int rc = p.waitFor();

System.out.println("STDOUT: \""+Files.readString(stdout)+'"');

【讨论】:

  • 问题已修复,并且 ``` pb.redirectErrorStream(true); ```真的很有帮助,谢谢!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多