获取系统信息

要通过oshi获取系统信息,首先需要导入oshi-core库。可以通过在Maven项目的pom.xml文件中添加以下依赖来实现:

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

在Java代码中,可以使用以下代码获取系统信息:

import oshi.SystemInfo;
import oshi.hardware.HardwareAbstractionLayer;
import oshi.software.os.OperatingSystem;

public class SystemInformation {
    public static void main(String[] args) {
        SystemInfo systemInfo = new SystemInfo();
        OperatingSystem operatingSystem = systemInfo.getOperatingSystem();
        HardwareAbstractionLayer hardware = systemInfo.getHardware();

        String os = operatingSystem.toString();
        String manufacturer = hardware.getComputerSystem().getManufacturer();
        String model = hardware.getComputerSystem().getModel();

        System.out.println("操作系统:" + os);
        System.out.println("制造商:" + manufacturer);
        System.out.println("型号:" + model);
    }
}

运行以上代码,将会输出系统的操作系统、制造商和型号。

获取硬件信息

通过oshi库,还可以获取硬件方面的信息,如CPU、内存、硬盘等。以下是获取一些常见硬件信息的示例:

CPU信息

import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;

public class CpuInformation {
    public static void main(String[] args) {
        SystemInfo systemInfo = new SystemInfo();
        CentralProcessor processor = systemInfo.getHardware().getProcessor();

        String cpuIdentifier = processor.getProcessorIdentifier().getName();
        String cpuArch = processor.getProcessorIdentifier().getArch();
        double cpuFreq = processor.getProcessorIdentifier().getVendorFreq() / 1e9;

        System.out.println("CPU标识符:" + cpuIdentifier);
        System.out.println("CPU架构:" + cpuArch);
        System.out.println("CPU频率:" + cpuFreq + " GHz");
    }
}

运行以上代码,将会输出CPU的标识符、架构和频率。

内存信息

import oshi.SystemInfo;
import oshi.hardware.GlobalMemory;

public class MemoryInformation {
    public static void main(String[] args) {
        SystemInfo systemInfo = new SystemInfo();
        GlobalMemory memory = systemInfo.getHardware().getMemory();

        long totalMemory = memory.getTotal();
        long availableMemory = memory.getAvailable();

        System.out.println("总内存:" + totalMemory / 1024 / 1024 + " MB");
        System.out.println("可用内存:" + availableMemory / 1024 / 1024 + " MB");
    }
}

运行以上代码,将会输出总内存和可用内存。

硬盘信息

import oshi.SystemInfo;
import oshi.hardware.HWDiskStore;

public class DiskInformation {
    public static void main(String[] args) {
        SystemInfo systemInfo = new SystemInfo();
        HWDiskStore[] disks = systemInfo.getHardware().getDiskStores();

        for (HWDiskStore disk : disks) {
            String diskName = disk.getName();
            long diskSize = disk.getSize() / 1024 / 1024 / 1024;

            System.out.println("硬盘名称:" + diskName);
            System.out.println("硬盘大小:" + diskSize + " GB");
        }
    }
}

运行以上代码,将会输出每个硬盘的名称和大小。


本文由轻山版权所有,禁止未经同意的情况下转发