เอาต์พุตไม่สมบูรณ์เกี่ยวกับ Java Runtime.getRuntime (). exec (คำสั่ง)
Oct 28 2020
ฉันต้องการสร้างแอปเช่น Jenkins Terminal:
และฉันใช้ Java Runtime.getRuntime().exec(command)เพื่อดำเนินการคำสั่งพบว่าผลลัพธ์ไม่สมบูรณ์
texthell.sh:
# textshell.sh
echo "wwwwwww";
sleep 2
ls
ตัวอย่างเช่นเมื่อฉันเรียกใช้งาน texthell.sh ในเทอร์มินัล mac ของฉันsh -x testshell.sh ผลลัพธ์:
+ echo wwwwwww
wwwwwww
+ sleep 2
+ ls
testshell.sh
แต่เมื่อฉันดำเนินการโดย java Java Runtime.getRuntime().exec("sh -x testshell.sh") ผลลัพธ์:
wwwwwww
testshell.sh
เชลล์อาร์ก-xดูเหมือนไร้ประโยชน์
จะแก้ไขได้อย่างไร?
คำตอบ
1 DuncG Oct 28 2020 at 13:35
ดังที่ @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)+'"');