如何使管道使用Runtime.exec()?考慮以下代碼:String commandf = "ls /etc | grep release";try {
// Execute the command and wait for it to complete
Process child = Runtime.getRuntime().exec(commandf);
child.waitFor();
// Print the first 16 bytes of its output
InputStream i = child.getInputStream();
byte[] b = new byte[16];
i.read(b, 0, b.length);
System.out.println(new String(b));} catch (IOException e) {
e.printStackTrace();
System.exit(-1);}該程序的輸出是:/etc:adduser.co當(dāng)然,當(dāng)我從shell運(yùn)行時(shí),它按預(yù)期工作:poundifdef@parker:~/rabbit_test$ ls /etc | grep release
lsb-release互聯(lián)網(wǎng)告訴我,由于管道行為不是跨平臺(tái)的,在Java工廠生產(chǎn)Java的聰明人不能保證管道工作。我該怎么做?我不打算使用Java構(gòu)造來(lái)進(jìn)行所有的解析,而不是grep和sed,因?yàn)槿绻蚁敫淖冋Z(yǔ)言,我將被迫用該語(yǔ)言重寫我的解析代碼,這完全是不可能的。如何讓Java在調(diào)用shell命令時(shí)進(jìn)行管道和重定向?
如何使管道使用Runtime.exec()?
開(kāi)滿天機(jī)
2019-06-20 15:40:19