Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/346.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
关于Java Runtime.getRuntime().exec(命令)的输出不完整_Java_Terminal - Fatal编程技术网

关于Java Runtime.getRuntime().exec(命令)的输出不完整

关于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

我想构建一个类似Jenkins terminal的应用程序:

我使用Java
Runtime.getRuntime().exec(command)
执行命令,发现输出不完整

textshell.sh:

# textshell.sh
echo "wwwwwww";
sleep 2
ls
例如: 当我在mac终端中执行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
似乎没有用


如何修复它?

正如@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);````真的很有帮助,谢谢!!