公司项目需要获取Windows和Linux系统下的CPU温度和硬盘温度,查阅了大量资料和技术,在原作者profesorfalken的jSensors(原项目自2019年已停止更新)的基础上,在Windows方面集成了两个库:
库名称 | 版本号 | 支持的.NET版本 |
---|---|---|
LibreHardwareMonitorLib.dll | 0.9.4 | 4.7.2+ |
OpenHardwareMonitorLib.dll | 0.9.3 | 2.0 |
在Linux方面也修复了若干问题,并封装成了新的开源项目,最终形成新版的jSensors
话不多说,要使用jSensors,第一步引入maven依赖:
<dependency>
<groupId>io.github.pandalxb</groupId>
<artifactId>jSensors</artifactId>
<version>1.0.0</version>
</dependency>
调用代码:
package io.github.pandalxb.test;
import io.github.pandalxb.jsensors.JSensors;
import io.github.pandalxb.jsensors.model.components.Components;
import io.github.pandalxb.jsensors.model.components.Cpu;
import io.github.pandalxb.jsensors.model.components.Disk;
import io.github.pandalxb.jsensors.model.sensors.Temperature;
import java.util.List;
public class JSensorsTest {
public static void main(String[] args) {
Components components = JSensors.get.components();
List<Cpu> cpus = components.cpus;
if (cpus != null) {
for (final Cpu cpu : cpus) {
System.out.println("Found CPU component: " + cpu.name);
if (cpu.sensors != null) {
System.out.println("Sensors: ");
//Print temperatures
List<Temperature> temps = cpu.sensors.temperatures;
for (final Temperature temp : temps) {
System.out.println(temp.name + ": " + temp.value + " C");
}
}
}
}
List<Disk> disks = components.disks;
if (disks != null) {
for (final Disk disk : disks) {
System.out.println("Found Disk component: " + disk.name);
if (disk.sensors != null) {
System.out.println("Sensors: ");
//Print temperatures
List<Temperature> temps = disk.sensors.temperatures;
for (final Temperature temp : temps) {
System.out.println(temp.name + ": " + temp.value + " C");
}
}
}
}
}
}
打印结果输出如下:
Found CPU component: Intel Core i5-4590
Sensors:
Temp Core Max: 51.0 C
Temp Core Average: 50.0 C
Temp CPU Core #1: 50.0 C
Temp CPU Core #2: 51.0 C
Temp CPU Core #3: 51.0 C
Temp CPU Core #4: 48.0 C
Temp CPU Package: 51.0 C
Temp CPU Core #1 Distance to TjMax: 50.0 C
Temp CPU Core #2 Distance to TjMax: 49.0 C
Temp CPU Core #3 Distance to TjMax: 49.0 C
Temp CPU Core #4 Distance to TjMax: 52.0 C
Found Disk component: SanDisk SSD PLUS 120GB
Sensors:
Temp Temperature: 26.0 C
Found Disk component: WDC WD10EZEX-08WN4A0
Sensors:
Temp Temperature: 29.0 C
注意:Windows需要以管理员身份运行java程序,Linux需要以Root用户运行java程序
Github地址:GitHub - pandalxb/jSensors: Monitorize all the hardware sensors of your PC using Java
相关项目:GitHub - pandalxb/jPowerShell: Simple Java API to interact with PowerShell console
喜欢的朋友帮忙在Github上点个星(Star),有问题欢迎提出Issue,也欢迎PR来改进和贡献项目