使用 Java 获取电脑性能参数

2023-12-14 13:03:33

Java内置的api 不能直接获取电脑的参数,需要借助第三方工具 oshi

JavaSE 方式

所需要的 jar
com.github.oshi:oshi-core:5.8.0net.java.dev.jna:jna:5.9.0net.java.dev.jna:jna-platform:5.9.0
org.slf4j:slf4j-api:1.7.21org.slf4j:slf4j-simple:1.7.21

实现

package com.test;

import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;
import oshi.hardware.GlobalMemory;
import oshi.hardware.HardwareAbstractionLayer;

public class SystemInfoTest { 

    public static void main(String[] args) {
        // 创建 SystemInfo 对象
        SystemInfo systemInfo = new SystemInfo();

        // 获取硬件相关信息
        HardwareAbstractionLayer hardware = systemInfo.getHardware();
        CentralProcessor processor = hardware.getProcessor();
        GlobalMemory memory = hardware.getMemory();

        // 打印 CPU 信息
        System.out.println("CPU 型号: " + processor.getProcessorIdentifier().getName());

        // 打印内存信息
        System.out.println("内存大小: " + memory.getTotal() / (1024L * 1024L) + " MB");

        // 打印显卡信息
        System.out.println("显卡信息: " + hardware.getGraphicsCards());

        // 打印声卡信息
        System.out.println("声卡信息: " + hardware.getSoundCards());
    }
}

SpringBoot 方式

所需要的依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>com.github.oshi</groupId>
    <artifactId>oshi-core</artifactId>
    <version>6.4.2</version>
</dependency>

<dependency>
    <groupId>net.java.dev.jna</groupId>
    <artifactId>jna</artifactId>
    <version>5.13.0</version>
</dependency>
<dependency>
    <groupId>net.java.dev.jna</groupId>
    <artifactId>jna-platform</artifactId>
    <version>5.13.0</version>
</dependency>

实现

package com.example.demomaven;

import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;
import oshi.hardware.GlobalMemory;
import oshi.hardware.HardwareAbstractionLayer;

public class Demo {
    public static void main(String[] args) {
        // 创建 SystemInfo 对象
        SystemInfo systemInfo = new SystemInfo();

        // 获取硬件相关信息
        HardwareAbstractionLayer hardware = systemInfo.getHardware();
        CentralProcessor processor = hardware.getProcessor();
        GlobalMemory memory = hardware.getMemory();

        // 打印 CPU 信息
        System.out.println("CPU 型号: " + processor.getProcessorIdentifier().getName());

        // 打印内存信息
        System.out.println("内存大小: " + memory.getTotal() / (1024L * 1024L) + " MB");

        // 打印显卡信息
        System.out.println("显卡信息: " + hardware.getGraphicsCards());

        // 打印声卡信息
        System.out.println("声卡信息: " + hardware.getSoundCards());
    }
}

文章来源:https://blog.csdn.net/weixin_46047612/article/details/134992054
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。