java获取cpu温度以及内存使用率
本文是使用oshi获取cpu温度,但是好像是因为有些硬件没有开启什么接口导致无法获取cpu温度。网上找了一下要下载一个软件才能获取于是就写一个启动这个软件的方法。
软件——>>链接: https://openhardwaremonitor.org/
<!-- https://mvnrepository.com/artifact/com.github.oshi/oshi-core -->
<dependency>
<groupId>com.github.oshi</groupId>
<artifactId>oshi-core</artifactId>
<version>6.4.0</version>
</dependency>
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna</artifactId>
<version>5.9.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.java.dev.jna/jna-platform -->
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna-platform</artifactId>
<version>5.6.0</version>
</dependency>
public static String getComputerInformation() throws Exception {
String msg;
SystemInfo systemInfo = new SystemInfo();
Runtime mt =Runtime.getRuntime();
boolean flag = false;
String keyWord = "OpenHardwareMonitor.exe";
Process process = mt.exec("cmd /c Tasklist");
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String s;
while ((s = in.readLine()) != null) {
if (s.startsWith(keyWord)) {
flag = true;
break;
}
}
if (!flag) {
File myfile =new File("你的OpenHardwareMonitor软件路径","OpenHardwareMonitor.exe");
mt.exec(myfile.getAbsolutePath());
}
//这里不知道为什么要睡眠一下才能获取到
Thread.sleep(5000);
Sensors sensors = systemInfo.getHardware().getSensors();
double cpuTemperature = sensors.getCpuTemperature();
long megaByte = 1024L * 1024L;
MemoryMXBean memoryMxBean = ManagementFactory.getMemoryMXBean();
MemoryUsage heapMemoryUsage = memoryMxBean.getHeapMemoryUsage();
long usedHeapMemory = heapMemoryUsage.getUsed();
long maxHeapMemory = heapMemoryUsage.getMax();
double heapMemoryUsagePercentage = ((double) usedHeapMemory / maxHeapMemory) * 100.0;
msg = "cpu温度:" + cpuTemperature + "。 已使用堆内存:" + usedHeapMemory / megaByte + "。 最大堆内存:" + maxHeapMemory / megaByte + "。 堆内存使用百分比:" + heapMemoryUsagePercentage;
return msg;
}