java 运行shell 得到 linux cpu的使用率

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);
  }
 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值