关于Java Runtime.getRuntime().exec(命令)的输出不完整
我想构建一个类似Jenkins terminal的应用程序: 我使用Java关于Java Runtime.getRuntime().exec(命令)的输出不完整,java,terminal,Java,Terminal,我想构建一个类似Jenkins terminal的应用程序: 我使用JavaRuntime.getRuntime().exec(command)执行命令,发现输出不完整 textshell.sh: # textshell.sh echo "wwwwwww"; sleep 2 ls 例如: 当我在mac终端中执行textshell.sh时,输出: + echo wwwwwww wwwwwww + sleep 2 + ls testshell.sh 但是当我通过javaja
Runtime.getRuntime().exec(command)
执行命令,发现输出不完整
textshell.sh:
# textshell.sh
echo "wwwwwww";
sleep 2
ls
例如:
当我在mac终端中执行textshell.sh时,输出:
+ echo wwwwwww
wwwwwww
+ sleep 2
+ ls
testshell.sh
但是当我通过javajava Runtime.getRuntime().exec(“sh-x testshell.sh”)
执行时,输出:
wwwwwww
testshell.sh
shell args-x
似乎没有用
如何修复它?正如@Joachim Sauer指出的那样,您没有阅读STDERR,因此错过了
set-x
输出的回波输出行。调整代码以访问进程。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)+'"');
似乎带“+”前缀的行被打印到了stderr。请确保使用(并显示)标准输出和标准错误流。尝试运行此
Runtime.getRuntime().exec(新字符串[]{“sh”、“-x”、“testshell.sh”}
读取标准错误流并修复问题,感谢已修复的lotproblem和``pb.redirectErrorStream(true);````真的很有帮助,谢谢!!