我将调用通过管道连接的命令行程序。这在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;
}
如果我执行 cat file | 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等。我该如何解决这个问题并获取输出的最终结果?