java获取cpu温度

本文介绍了如何在Java中使用Oshi库获取CPU温度,由于某些硬件限制,作者提到需借助OpenHardwareMonitor软件。同时展示了如何获取内存使用情况,包括堆内存的使用百分比。
摘要由CSDN通过智能技术生成

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;
  }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值