日期:2014-05-16  浏览次数:20543 次

JAVA 调用LINUX命令类
这个是我写的系统采集类实现了CPU个数,CPU频率,内存信息,磁盘信息,CPU利用率,内存利用率,磁盘利用率,系统启动时间的获得
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.fenghuo.jsnmp.logic.task;
import java.io.*;
import java.util.StringTokenizer;
/**
* 用于执行linux命令
* @author huangxf
*
*/
public class LinuxExec {
    /**
     * 获取cpu使用情况
     * @return
     * @throws Exception
     */
    public double getCpuUsage() throws Exception {
        double cpuUsed = 0;
        Runtime rt = Runtime.getRuntime();
        Process p = rt.exec("top -b -n 1");// 调用系统的“top"命令
        BufferedReader in = null;
        try {
            in = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String str = null;
            String[] strArray = null;
            while ((str = in.readLine()) != null) {
                int m = 0;
                if (str.indexOf(" R ") != -1) {// 只分析正在运行的进程,top进程本身除外 &&
                    strArray = str.split(" ");
                    for (String tmp : strArray) {
                        if (tmp.trim().length() == 0) {
                            continue;
                        }
                        if (++m == 9) {// 第9列为CPU的使用百分比(RedHat
                            cpuUsed += Double.parseDouble(tmp);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            in.close();
        }
        return cpuUsed;
    }
    /**
     * 内存监控
     * @return
  &nbs