java获取linux服务器cpu,内存使用率
时间: 2023-09-18 16:11:35 浏览: 123
可以使用Java的Runtime类和Process类来获取Linux服务器的CPU和内存使用率。具体实现方法如下:
1. 获取CPU使用率:
```java
public static double getCpuUsage() {
try {
Process process = Runtime.getRuntime().exec("top -b -n1");
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = reader.readLine();
while (line != null) {
if (line.startsWith("Cpu(s)")) {
String[] cpuInfo = line.split("\\s+");
double idleCpuUsage = Double.parseDouble(cpuInfo[4]);
double totalCpuUsage = 100 - idleCpuUsage;
return totalCpuUsage;
}
line = reader.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
return 0;
}
```
2. 获取内存使用率:
```java
public static double getMemoryUsage() {
try {
Process process = Runtime.getRuntime().exec("free -m");
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = reader.readLine();
if (line != null) {
String[] memoryInfo = line.split("\\s+");
double totalMemory = Double.parseDouble(memoryInfo[1]);
double usedMemory = Double.parseDouble(memoryInfo[2]);
double memoryUsage = usedMemory / totalMemory * 100;
return memoryUsage;
}
} catch (IOException e) {
e.printStackTrace();
}
return 0;
}
```
以上代码通过执行Linux命令获取CPU和内存使用率,并返回一个double类型的数值,表示使用率的百分比。需要注意的是,这些命令的输出格式可能会因Linux版本而异,需要根据实际情况进行调整。
阅读全文