Output incompleto su Java Runtime.getRuntime (). Exec (comando)
Voglio creare un'app come il terminale Jenkins:
E uso Java Runtime.getRuntime().exec(command)per eseguire il comando, scopro che l'output è incompleto.
textshell.sh:
# textshell.sh
echo "wwwwwww";
sleep 2
ls
Ad esempio: quando eseguo textshell.sh nel mio terminale Mac sh -x testshell.sh , output:
+ echo wwwwwww
wwwwwww
+ sleep 2
+ ls
testshell.sh
ma quando eseguo da java Java Runtime.getRuntime().exec("sh -x testshell.sh") , output:
wwwwwww
testshell.sh
gli argomenti della shell -xsembrano inutili
Come posso risolverlo?
Risposte
Come sottolinea @Joachim Sauer, non stai leggendo STDERR, quindi perdi le righe dell'output dell'eco set -xdall'output. Modifica il tuo codice per accedere process.getErrorStream()anche a.
In alternativa puoi passare a ProcessBuilderse vuoi leggere il flusso di errore unito all'output:
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)+'"');