window下:
import com.sun.management.OperatingSystemMXBean;
import java.io.File;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.lang.management.ManagementFactory;
import java.util.ArrayList;
import java.util.List;
public class windowtest {
private static final int CPUTIME = 500;
private static final int PERCENT = 100;
private static final int FAULTLENGTH = 10;
//获取cpu占用情况
public static String getCpuRatioForWindows() {
try {
String procCmd = System.getenv("windir") + "\\system32\\wbem\\wmic.exe process get Caption,CommandLine,KernelModeTime,ReadOperationCount,ThreadCount,UserModeTime,WriteOperationCount";
// 取进程信息
long[] c0 = readCpu(Runtime.getRuntime().exec(procCmd));
Thread.sleep(CPUTIME);
long[] c1 = readCpu(Runtime.getRuntime().exec(procCmd));
if (c0 != null && c1 != null) {
long idletime = c1[0] - c0[0];
long busytime = c1[1] - c0[1];
return "CPU使用率:" + Double.valueOf(PERCENT * (busytime) * 1.0 / (busytime + idletime)).intValue() + "%";
} else {
return "CPU使用率:" + 0 + "%";
}
} catch (Exception ex) {
ex.printStackTrace();
return "CPU使用率:" + 0 + "%";
}
}
private static long[] readCpu(final Process proc) {
long[] retn = new long[2];
try {
proc.getOutputStream().close();
InputStreamReader ir = new InputStreamReader(proc.getInputStream());
LineNumberReader input = new LineNumberReader(ir);
String line = input.readLine();
if (line == null || line.length() < FAULTLENGTH) {
return null;
}
int capidx = line.indexOf("Caption");
int cmdidx = line.indexOf("CommandLine");
int rocidx = line.indexOf("ReadOperationCount");
int umtidx = line.indexOf("UserModeTime");
int kmtidx = line.indexOf("KernelModeTime");
int wocidx = line.indexOf("WriteOperationCount");
long idletime = 0;
long kneltime = 0;
long usertime = 0;
while ((line = input.readLine()) != null) {
if (line.length() < wocidx) {
continue;
}
// 字段出现顺序:Caption,CommandLine,KernelModeTime,ReadOperationCount,
// ThreadCount,UserModeTime,WriteOperation
String caption = substring(line, capidx, cmdidx - 1).trim();
String cmd = substring(line, cmdidx, kmtidx - 1).trim();
if (cmd.indexOf("wmic.exe") >= 0) {
continue;
}
String s1 = substring(line, kmtidx, rocidx - 1).trim();
String s2 = substring(line, umtidx, wocidx - 1).trim();
if (caption.equals("System Idle Process") || caption.equals("System")) {
if (s1.length() > 0)
idletime += Long.valueOf(s1).longValue();
if (s2.length() > 0)
idletime += Long.valueOf(s2).longValue();
continue;
}
if (s1.length() > 0)
kneltime += Long.valueOf(s1).longValue();
if (s2.length() > 0)
usertime += Long.valueOf(s2).longValue();
}
retn[0] = idletime;
retn[1] = kneltime + usertime;
return retn;
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
proc.getInputStream().close();
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
/**
* 由于String.subString对汉字处理存在问题(把一个汉字视为一个字节),因此在 包含汉字的字符串时存在隐患,现调整如下:
*
* @param src 要截取的字符串
* @param start_idx 开始坐标(包括该坐标)
* @param end_idx 截止坐标(包括该坐标)
* @return java.lang.String
* @author loulan
*/
private static String substring(String src, int start_idx, int end_idx) {
byte[] b = src.getBytes();
String tgt = "";
for (int i = start_idx; i <= end_idx; i++) {
tgt += (char) b[i];
}
return tgt;
}
/**
* 获取内存使用率
*
* @return java.lang.String
* @author loulan
*/
public static String getMemery() {
// 用管理工厂获取操作系统属性
OperatingSystemMXBean operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
// 总的物理内存+虚拟内存
long totalvirtualMemory = operatingSystemMXBean.getTotalSwapSpaceSize();
// 剩余的物理内存
long freePhysicalMemorySize = operatingSystemMXBean.getFreePhysicalMemorySize();
Double compare = (Double) (1 - freePhysicalMemorySize * 1.0 / totalvirtualMemory) * 100;
return "内存已使用:" + compare.intValue() + "%";
}
/**
* 获取文件系统使用率
*
* @return java.util.List
* @author loulan
*/
public static List getDisk() {
// 操作系统
List list = new ArrayList();
for (char c = 'A'; c <= 'Z'; c++) {
String dirName = c + ":/";
File win = new File(dirName);
if (win.exists()) {
long total = (long) win.getTotalSpace();
long free = (long) win.getFreeSpace();
Double compare = (Double) (1 - free * 1.0 / total) * 100;
String str = c + ":盘 已使用 " + compare.intValue() + "%";
list.add(str);
}
}
return list;
}
public static void main(String[] args) {
List a=windowtest.getDisk();
a.forEach(zhi-> System.out.println(zhi));
}
}
linux下:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.*;
public class linuxtest {
/**
* 获取磁盘使用率
*
* @return int
* @author loulan
*/
public static int getDiskUsage() throws Exception {
double totalHD = 0;
double usedHD = 0;
Runtime rt = Runtime.getRuntime();
// df -hl 查看硬盘空间
Process p = rt.exec("df -hl");
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;
strArray = str.split(" ");
for (String tmp : strArray) {
if (tmp.trim().length() == 0)
continue;
++m;
if (tmp.indexOf("G") != -1) {
if (m == 2) {
if (!tmp.equals("") && !tmp.equals("0"))
totalHD += Double.parseDouble(tmp.substring(0, tmp.length() - 1)) * 1024;
}
if (m == 3) {
if (!tmp.equals("none") && !tmp.equals("0"))
usedHD += Double.parseDouble(tmp.substring(0, tmp.length() - 1)) * 1024;
}
}
if (tmp.indexOf("M") != -1) {
if (m == 2) {
if (!tmp.equals("") && !tmp.equals("0"))
totalHD += Double.parseDouble(tmp.substring(0, tmp.length() - 1));
}
if (m == 3) {
if (!tmp.equals("none") && !tmp.equals("0"))
usedHD += Double.parseDouble(tmp.substring(0, tmp.length() - 1));
}
}
}
}
} catch (Exception e) {
e.getStackTrace();
} finally {
in.close();
}
// 保留2位小数
double precent = (usedHD / totalHD) * 100;
BigDecimal b1 = new BigDecimal(precent);
precent = b1.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
return (int) precent;
}
/**
* 获取cpu使用率
*
* @return int
* @author loulan
*/
public static int getCpuUsage() {
try {
Map, ?> map1 = linuxtest.getCpuinfo();
Thread.sleep(5 * 1000);
Map, ?> map2 = linuxtest.getCpuinfo();
long user1 = Long.parseLong(map1.get("user").toString());
long nice1 = Long.parseLong(map1.get("nice").toString());
long system1 = Long.parseLong(map1.get("system").toString());
long idle1 = Long.parseLong(map1.get("idle").toString());
long user2 = Long.parseLong(map2.get("user").toString());
long nice2 = Long.parseLong(map2.get("nice").toString());
long system2 = Long.parseLong(map2.get("system").toString());
long idle2 = Long.parseLong(map2.get("idle").toString());
long total1 = user1 + system1 + nice1;
long total2 = user2 + system2 + nice2;
float total = total2 - total1;
long totalIdle1 = user1 + nice1 + system1 + idle1;
long totalIdle2 = user2 + nice2 + system2 + idle2;
float totalidle = totalIdle2 - totalIdle1;
float cpusage = (total / totalidle) * 100;
return (int) cpusage;
} catch (InterruptedException e) {
e.printStackTrace();
}
return 0;
}
/**
* 获取CPU使用信息
*
* @return java.util.Map
* @author loulan
*/
public static Map, ?> getCpuinfo() {
InputStreamReader inputs = null;
BufferedReader buffer = null;
Map map = new HashMap();
try {
inputs = new InputStreamReader(new FileInputStream("/proc/stat"));
buffer = new BufferedReader(inputs);
String line = "";
while (true) {
line = buffer.readLine();
if (line == null) {
break;
}
if (line.startsWith("cpu")) {
StringTokenizer tokenizer = new StringTokenizer(line);
List temp = new ArrayList();
while (tokenizer.hasMoreElements()) {
String value = tokenizer.nextToken();
temp.add(value);
}
map.put("user", temp.get(1));
map.put("nice", temp.get(2));
map.put("system", temp.get(3));
map.put("idle", temp.get(4));
map.put("iowait", temp.get(5));
map.put("irq", temp.get(6));
map.put("softirq", temp.get(7));
map.put("stealstolen", temp.get(8));
break;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
buffer.close();
inputs.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
return map;
}
/**
* 获取内存使用率
*
* @return int
* @author loulan
*/
public static int getMemoryUsage() {
Map map = new HashMap();
InputStreamReader inputs = null;
BufferedReader buffer = null;
try {
inputs = new InputStreamReader(new FileInputStream("/proc/meminfo"));
buffer = new BufferedReader(inputs);
String line = "";
while (true) {
line = buffer.readLine();
if (line == null)
break;
int beginIndex = 0;
int endIndex = line.indexOf(":");
if (endIndex != -1) {
String key = line.substring(beginIndex, endIndex);
beginIndex = endIndex + 1;
endIndex = line.length();
String memory = line.substring(beginIndex, endIndex);
String value = memory.replace("kB", "").trim();
map.put(key, value);
}
}
long memTotal = Long.parseLong(map.get("MemTotal").toString());
long memFree = Long.parseLong(map.get("MemFree").toString());
long memused = memTotal - memFree;
long buffers = Long.parseLong(map.get("Buffers").toString());
long cached = Long.parseLong(map.get("Cached").toString());
double usage = (double) (memused - buffers - cached) / memTotal * 100;
return (int) usage;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
buffer.close();
inputs.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
return 0;
}
}