java获取linux服务器cpu,内存使用率
时间: 2023-09-18 07:11:38 浏览: 165
可以使用Java代码调用Linux命令获取CPU和内存使用率。
获取CPU使用率:
```java
public static double getCpuUsage() throws IOException {
double cpuUsage = 0.0;
Process process = Runtime.getRuntime().exec("top -b -n1");
try(BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
String line;
while((line = reader.readLine()) != null) {
if(line.startsWith("Cpu(s)")) {
String[] cpuInfo = line.split("\\s+");
double user = Double.parseDouble(cpuInfo[1].replace("%",""));
double sys = Double.parseDouble(cpuInfo[3].replace("%",""));
double idle = Double.parseDouble(cpuInfo[7].replace("%",""));
cpuUsage = (user + sys) / (user + sys + idle) * 100.0;
}
}
}
return cpuUsage;
}
```
获取内存使用率:
```java
public static double getMemoryUsage() throws IOException {
double memoryUsage = 0.0;
Process process = Runtime.getRuntime().exec("free -m");
try(BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
String line;
while((line = reader.readLine()) != null) {
if(line.startsWith("Mem:")) {
String[] memoryInfo = line.split("\\s+");
double used = Double.parseDouble(memoryInfo[2]);
double total = Double.parseDouble(memoryInfo[1]);
memoryUsage = used / total * 100.0;
}
}
}
return memoryUsage;
}
```
这里使用了Linux命令`top -b -n1`和`free -m`来获取CPU和内存使用率。`-b`表示以批处理模式运行,不需要交互式输入。`-n1`表示只执行一次。获取到命令输出后,使用Java代码解析命令输出并计算出使用率。
阅读全文