我正在调用通过管道连接的命令行程序。所有这些肯定可以在Linux上运行。
我的方法:
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。我猜想这个问题取决于输出格式化命令,例如 head , tail , wc
等。我如何解决这个问题并获得输出的最终结果?