日期:2014-05-16 浏览次数:20828 次
Process process = Runtime.getRuntime().exec("top -b -n 1");
?
//已测试
?
//运行shell 得到 linux cpu的使用率
?public static String getCpuRateForLinux() {
??InputStream is = null;
??InputStreamReader isr = null;
??BufferedReader brStat = null;
??StringTokenizer tokenStat = null;
??try {
???Process process = Runtime.getRuntime().exec("top -b -n 1");
???is = process.getInputStream();
???isr = new InputStreamReader(is);
???brStat = new BufferedReader(isr);
???osVersion = System.getProperty("os.version");
???System.out.println("yang osVersion:"+osVersion);
??
???if (osVersion.startsWith("2.6")){
????System.out.println("yang osVersion.startsWith(2.6)");
????String temp;
????int end;
????//取得cpu空闲 idle
????Float usage =0.0f;
????while((temp = brStat.readLine())!=null){
?????if(temp.indexOf("id")>-1){
??????end = temp.indexOf("id");
??????temp = temp.substring(end-9,end);
??????temp = temp.substring(temp.lastIndexOf(",")+1,temp.lastIndexOf("%"));
??????usage = Float.valueOf(temp.trim());
??????break;
?????}
????}
????//取得cpu空闲 idle
????
????System.out.println("osVersion 2.6:"+(1.0f - usage/ 100));
????//保留3位小数
????return Math.round((1.0f - usage/ 100)*1000)/1000 +"";
???}
??}catch (IOException ioe) {
???System.out.println(ioe.getMessage());
???freeResource(is, isr, brStat);
???return "1";
??} finally {
???freeResource(is, isr, brStat);
??}
?}