Java Runtime.getRuntime ()। Exec (कमांड) के बारे में अधूरा आउटपुट
मैं जेनकिंस टर्मिनल की तरह एक ऐप बनाना चाहता हूं:
और मैं Runtime.getRuntime().exec(command)कमांड को निष्पादित करने के लिए जावा का उपयोग करता हूं , पता करें कि आउटपुट अधूरा है।
textshell.sh:
# textshell.sh
echo "wwwwwww";
sleep 2
ls
उदाहरण के लिए: जब मैं अपने मैक टर्मिनल में texthell.sh निष्पादित करता हूं sh -x testshell.sh , तो आउटपुट:
+ echo wwwwwww
wwwwwww
+ sleep 2
+ ls
testshell.sh
लेकिन जब मैं जावा Java Runtime.getRuntime().exec("sh -x testshell.sh") , आउटपुट द्वारा निष्पादित करता हूं :
wwwwwww
testshell.sh
शेल आर्ग्स -xबेकार लगता है
मेरे द्वारा यह कैसे किया जा सकता है?
जवाब
जैसा कि @Joachim Sauer बताते हैं कि आप STDERR नहीं पढ़ रहे हैं, इसलिए आउटपुट से इको आउटपुट की लाइनें याद आती हैं set -x। 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)+'"');