我正在调用通过管道连接的命令行程序。所有这一切都适用于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