我正在調用通過管道連接的命令行程序。所有這一切都適用於Linux。Java exec()不返回管道連接命令的預期結果
我的方法:
protected String execCommand(String command) throws IOException {
String line = null;
if (command.length() > 0) {
Process child = Runtime.getRuntime().exec(command);
InputStream lsOut = child.getInputStream();
InputStreamReader r = new InputStreamReader(lsOut);
BufferedReader in = new BufferedReader(r);
String readline = null;
while ((readline = in.readLine()) != null) {
line = line + readline;
}
}
return line;
}
如果我打電話給一些貓文件| grep asd,我得到了預期的結果。但並非所有的命令都能正常工作比如這個:
cat /proc/cpuinfo | wc -l
或本:
cat /proc/cpuinfo | grep "model name" | head -n 1 | awk -F":" '{print substr($2, 2, length($2))}
方法將返回null。我猜這個問題取決於輸出格式化命令,如頭,尾,wc等我怎麼能解決這個問題,並得到最終結果的輸出?
無用的(使用* 3)的'cat'。 – 2010-01-18 20:35:01
@丹尼斯 - 的確如此。發現得好! – 2010-01-18 20:39:35
@Bobby我試過了,這沒有幫助。 – Pawka 2010-01-18 20:54:11