CPU使用率:
InputStream is = null;
InputStreamReader isr = null;
BufferedReader brStat = null;
StringTokenizer tokenStat = null; // 用来分隔String的应用类
try {
System.out.println("Get usage rate of CUP : ");
Process process = Runtime.getRuntime().exec("top -b"); // top命令是Linux下常用的性能分析工具,能够实时显示系统中各个进程的资源使用情况。
is = process.getInputStream(); // 可以读取新开启的程序的 System.out.print 输出的内容
isr = new InputStreamReader(is); // 将字节流转换为字符流。
brStat = new BufferedReader(isr); // BufferedReader 流能够读取文本行
brStat.readLine();
brStat.readLine();
tokenStat = new StringTokenizer(brStat.readLine());
tokenStat.nextToken();
System.out.println("用户空间占用CPU的百分比 : " + tokenStat.nextToken());
tokenStat.nextToken();
System.out.println("内核空间占用CPU的百分比 : " + tokenStat.nextToken());
tokenStat.nextToken();
tokenStat.nextToken();
tokenStat.nextToken();
String cpuFree = tokenStat.nextToken();
System.out.println("空闲CPU百分比 : " + cpuFree);
Float free = new Float(free);
Float usage=1 - free.floatValue() / 100
//内存:
OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory
.getOperatingSystemMXBean();
// 虚拟内存
long totalVirtualMemory = osmxb.getTotalSwapSpaceSize() / mb;
// 总的物理内存
long totalMemorySize = osmxb.getTotalPhysicalMemorySize() / mb;
// 剩余的物理内存
long freePhysicalMemorySize = osmxb.getFreePhysicalMemorySize() / mb;
// 已使用的物理内存
long usedMemory = (osmxb.getTotalPhysicalMemorySize() - osmxb
.getFreePhysicalMemorySize()) / mb;
磁盘空间:
Process pro = null;
Runtime r = Runtime.getRuntime();
String command = "df -h";
pro = r.exec(command);
BufferedReader in = new BufferedReader(new InputStreamReader(
pro.getInputStream()));
String line = null;
System.out.println("目前所有文件系统的可用空间及使用情形 Filesystem Size Used Avail Use% Mounted on");
while ((line = in.readLine()) != null) {
// String[] Info = line.split("\\s+");
System.out.println(in.readLine());
}
in.close();
pro.destroy();