java获取系统CPU和内存和磁盘使用率
时间: 2024-01-14 09:04:41 浏览: 51
您可以使用Java中的ManagementFactory类来获取系统的CPU和内存使用率。以下是获取系统CPU使用率的示例代码:
```
import java.lang.management.ManagementFactory;
import com.sun.management.OperatingSystemMXBean;
public class SystemInfo {
public static void main(String[] args) {
OperatingSystemMXBean operatingSystemMXBean = (com.sun.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
double cpuLoad = operatingSystemMXBean.getSystemCpuLoad() * 100;
System.out.println("CPU使用率: " + cpuLoad + "%");
}
}
```
以下是获取系统内存使用率的示例代码:
```
import java.lang.management.ManagementFactory;
import com.sun.management.OperatingSystemMXBean;
public class SystemInfo {
public static void main(String[] args) {
OperatingSystemMXBean operatingSystemMXBean = (com.sun.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
long totalMemorySize = operatingSystemMXBean.getTotalPhysicalMemorySize();
long freePhysicalMemorySize = operatingSystemMXBean.getFreePhysicalMemorySize();
double memoryLoad = (totalMemorySize - freePhysicalMemorySize) * 100 / totalMemorySize;
System.out.println("内存使用率: " + memoryLoad + "%");
}
}
```
以下是获取系统磁盘使用率的示例代码:
```
import java.io.File;
import java.io.IOException;
public class SystemInfo {
public static void main(String[] args) throws IOException {
File file = new File("/");
long totalSpace = file.getTotalSpace();
long freeSpace = file.getFreeSpace();
long usableSpace = file.getUsableSpace();
double diskLoad = (totalSpace - freeSpace) * 100 / totalSpace;
System.out.println("磁盘使用率: " + diskLoad + "%");
}
}
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)