获取cpu使用信息:
public static float getCpuInfo() throws IOException, InterruptedException
{
File file = new File("/proc/stat");
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(file)));
StringTokenizer token = new StringTokenizer(br.readLine());
token.nextToken();
int user1 = Integer.parseInt(token.nextToken());
int nice1 = Integer.parseInt(token.nextToken());
int sys1 = Integer.parseInt(token.nextToken());
int idle1 = Integer.parseInt(token.nextToken());
log.debug("user1===" + user1);
log.debug("nice1===" + nice1);
log.debug("sys1===" + sys1);
log.debug("idle1===" + idle1);
Thread.sleep(1000);
br = new BufferedReader(
new InputStreamReader(new FileInputStream(file)));
token = new StringTokenizer(br.readLine());
token.nextToken();
int user2 = Integer.parseInt(token.nextToken());
int nice2 = Integer.parseInt(token.nextToken());
int sys2 = Integer.parseInt(token.nextToken());
int idle2 = Integer.parseInt(token.nextToken());
log.debug("user2===" + user2);
log.debug("nice2===" + nice2);
log.debug("sys2===" + sys2);
log.debug("idle2===" + idle2);
float cpuvalue = (user2 + nice2 + sys2 + idle2)
-
(user1 + nice1 + sys1 + idle1);
if (cpuvalue == 0)
{
return 0;
}
log.debug("cpuvalue===" + cpuvalue);
float getCpuvalue = (float) ( (user2 + sys2 + nice2)
- (user1 + sys1 + nice1))
/
cpuvalue;
log.debug("getCpuvalue===" + getCpuvalue);
return getCpuvalue;
}
获取进程信息:
public static float[] getLoadAvgInfo() throws Exception
{
File file = new File("/proc/loadavg");
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(file)));
String avgLine = br.readLine();
String[] arvArray = avgLine.split("//s", 0);
float[] floatAvgArray = new float[3];
floatAvgArray[0] = Float.parseFloat(arvArray[0]);
floatAvgArray[1] = Float.parseFloat(arvArray[1]);
floatAvgArray[2] = Float.parseFloat(arvArray[2]);
return floatAvgArray;
}