这是为了获取Linux下cpu使用率方法。 直接运行Linux命令返回的结果是0.33,可当我通过这个方法时返回显示是我在页面中确是0.0。 请各位高手帮我看看,那里有问题。小弟拜谢! [size=x-small]public double getCPUfactor() throws IOException { double cpuUsed = 0; Runtime rt = Runtime.getRuntime(); Process p = rt.exec("mpstat |grep all|awk '{print $4}'");// 调用linux系统的命令 BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(p.getInputStream())); String str = null; while ((str = in.readLine()) != null) { cpuUsed= Double.parseDouble(str); } p.waitFor(); } catch (Exception e) { e.printStackTrace(); } finally { in.close(); } return cpuUsed; }[/size][size=large][/size]
你那个只取了第一行
[code="java"]
in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String str = null;
while ((str = in.readLine()) != null) {
if(str.indexOf("%") != -1) return str;
///cpuUsed= Double.parseDouble(str);
}
[/code]
可能是命令没有返回,把str打印一下,看有没有值
因为用到了管道"|",inputstream我也不知道给重定向到哪去了
你试下直接调用shell
[code="java"]rt.exec(new String[]{"/bin/sh","-c","mpstat |grep all |awk '{print $4}'"});/[/code]