说明:使用的jar包:oshi-core,maven引入如下:

        <dependency><groupId>com.github.oshi</groupId><artifactId>oshi-core</artifactId><version>3.9.1</version></dependency><dependency><groupId>net.java.dev.jna</groupId><artifactId>jna</artifactId></dependency><dependency><groupId>net.java.dev.jna</groupId><artifactId>jna-platform</artifactId></dependency>

测试代码:


/** * Licensed to the Apache Software Foundation (ASF) under one or more* contributor license agreements.  See the NOTICE file distributed with* this work for additional information regarding copyright ownership.* The ASF licenses this file to You under the Apache License, Version 2.0* (the "License"); you may not use this file except in compliance with* the License.  You may obtain a copy of the License at**     http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.**/
package com.ruoyi.web.controller.tool;import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import oshi.PlatformEnum;
import oshi.SystemInfo;
import oshi.hardware.Baseboard;
import oshi.hardware.CentralProcessor;
import oshi.hardware.CentralProcessor.TickType;
import oshi.hardware.ComputerSystem;
import oshi.hardware.Display;
import oshi.hardware.Firmware;
import oshi.hardware.GlobalMemory;
import oshi.hardware.HWDiskStore;
import oshi.hardware.HWPartition;
import oshi.hardware.HardwareAbstractionLayer;
import oshi.hardware.NetworkIF;
import oshi.hardware.PowerSource;
import oshi.hardware.Sensors;
import oshi.hardware.SoundCard;
import oshi.hardware.UsbDevice;
import oshi.software.os.FileSystem;
import oshi.software.os.NetworkParams;
import oshi.software.os.OSFileStore;
import oshi.software.os.OSProcess;
import oshi.software.os.OperatingSystem;
import oshi.software.os.OperatingSystem.ProcessSort;
import oshi.util.FormatUtil;
import oshi.util.Util;
/**
* @desc:
* @name: SystemInfoTest.java
* @author: tompai
* @email:liinux@qq.com
* @createTime: 2020年3月12日 下午2:22:43
* @history:
* @version: v1.0
*/public class SystemInfoTest {public static void main(String[] args) {// Options: ERROR > WARN > INFO > DEBUG > TRACELogger LOG = LoggerFactory.getLogger(SystemInfoTest.class);LOG.info("Initializing System...");SystemInfo si = new SystemInfo();HardwareAbstractionLayer hal = si.getHardware();OperatingSystem os = si.getOperatingSystem();System.out.println(os);LOG.info("Checking computer system...");printComputerSystem(hal.getComputerSystem());LOG.info("Checking Processor...");printProcessor(hal.getProcessor());LOG.info("Checking Memory...");printMemory(hal.getMemory());LOG.info("Checking CPU...");printCpu(hal.getProcessor());LOG.info("Checking Processes...");printProcesses(os, hal.getMemory());LOG.info("Checking Sensors...");printSensors(hal.getSensors());LOG.info("Checking Power sources...");printPowerSources(hal.getPowerSources());LOG.info("Checking Disks...");printDisks(hal.getDiskStores());LOG.info("Checking File System...");printFileSystem(os.getFileSystem());LOG.info("Checking Network interfaces...");printNetworkInterfaces(hal.getNetworkIFs());LOG.info("Checking Network parameterss...");printNetworkParameters(os.getNetworkParams());// hardware: displaysLOG.info("Checking Displays...");printDisplays(hal.getDisplays());// hardware: USB devicesLOG.info("Checking USB Devices...");printUsbDevices(hal.getUsbDevices(true));}private static void printComputerSystem(final ComputerSystem computerSystem) {System.out.println("manufacturer: " + computerSystem.getManufacturer());System.out.println("model: " + computerSystem.getModel());System.out.println("serialnumber: " + computerSystem.getSerialNumber());final Firmware firmware = computerSystem.getFirmware();System.out.println("firmware:");System.out.println("  manufacturer: " + firmware.getManufacturer());System.out.println("  name: " + firmware.getName());System.out.println("  description: " + firmware.getDescription());System.out.println("  version: " + firmware.getVersion());
//      System.out.println("  release date: " + (firmware.getReleaseDate() == null ? "unknown": firmware.getReleaseDate() == null ? "unknown" : FormatUtil.formatDate(firmware.getReleaseDate())));final Baseboard baseboard = computerSystem.getBaseboard();System.out.println("baseboard:");System.out.println("  manufacturer: " + baseboard.getManufacturer());System.out.println("  model: " + baseboard.getModel());System.out.println("  version: " + baseboard.getVersion());System.out.println("  serialnumber: " + baseboard.getSerialNumber());}private static void printProcessor(CentralProcessor processor) {System.out.println(processor);System.out.println(" " + processor.getPhysicalPackageCount() + " physical CPU package(s)");System.out.println(" " + processor.getPhysicalProcessorCount() + " physical CPU core(s)");System.out.println(" " + processor.getLogicalProcessorCount() + " logical CPU(s)");System.out.println("Identifier: " + processor.getIdentifier());System.out.println("ProcessorID: " + processor.getProcessorID());}private static void printMemory(GlobalMemory memory) {System.out.println("Memory: " + FormatUtil.formatBytes(memory.getAvailable()) + "/"+ FormatUtil.formatBytes(memory.getTotal()));System.out.println("Swap used: " + FormatUtil.formatBytes(memory.getSwapUsed()) + "/"+ FormatUtil.formatBytes(memory.getSwapTotal()));}private static void printCpu(CentralProcessor processor) {System.out.println("Uptime: " + FormatUtil.formatElapsedSecs(processor.getSystemUptime()));System.out.println("Context Switches/Interrupts: " + processor.getContextSwitches() + " / " + processor.getInterrupts());long[] prevTicks = processor.getSystemCpuLoadTicks();System.out.println("CPU, IOWait, and IRQ ticks @ 0 sec:" + Arrays.toString(prevTicks));// Wait a second...Util.sleep(1000);long[] ticks = processor.getSystemCpuLoadTicks();System.out.println("CPU, IOWait, and IRQ ticks @ 1 sec:" + Arrays.toString(ticks));long user = ticks[TickType.USER.getIndex()] - prevTicks[TickType.USER.getIndex()];long nice = ticks[TickType.NICE.getIndex()] - prevTicks[TickType.NICE.getIndex()];long sys = ticks[TickType.SYSTEM.getIndex()] - prevTicks[TickType.SYSTEM.getIndex()];long idle = ticks[TickType.IDLE.getIndex()] - prevTicks[TickType.IDLE.getIndex()];long iowait = ticks[TickType.IOWAIT.getIndex()] - prevTicks[TickType.IOWAIT.getIndex()];long irq = ticks[TickType.IRQ.getIndex()] - prevTicks[TickType.IRQ.getIndex()];long softirq = ticks[TickType.SOFTIRQ.getIndex()] - prevTicks[TickType.SOFTIRQ.getIndex()];long steal = ticks[TickType.STEAL.getIndex()] - prevTicks[TickType.STEAL.getIndex()];long totalCpu = user + nice + sys + idle + iowait + irq + softirq + steal;System.out.format("User: %.1f%% Nice: %.1f%% System: %.1f%% Idle: %.1f%% IOwait: %.1f%% IRQ: %.1f%% SoftIRQ: %.1f%% Steal: %.1f%%%n",100d * user / totalCpu, 100d * nice / totalCpu, 100d * sys / totalCpu, 100d * idle / totalCpu,100d * iowait / totalCpu, 100d * irq / totalCpu, 100d * softirq / totalCpu, 100d * steal / totalCpu);System.out.format("CPU load: %.1f%% (counting ticks)%n", processor.getSystemCpuLoadBetweenTicks() * 100);System.out.format("CPU load: %.1f%% (OS MXBean)%n", processor.getSystemCpuLoad() * 100);double[] loadAverage = processor.getSystemLoadAverage(3);System.out.println("CPU load averages:" + (loadAverage[0] < 0 ? " N/A" : String.format(" %.2f", loadAverage[0]))+ (loadAverage[1] < 0 ? " N/A" : String.format(" %.2f", loadAverage[1]))+ (loadAverage[2] < 0 ? " N/A" : String.format(" %.2f", loadAverage[2])));// per core CPUStringBuilder procCpu = new StringBuilder("CPU load per processor:");double[] load = processor.getProcessorCpuLoadBetweenTicks();for (double avg : load) {procCpu.append(String.format(" %.1f%%", avg * 100));}System.out.println(procCpu.toString());}private static void printProcesses(OperatingSystem os, GlobalMemory memory) {System.out.println("Processes: " + os.getProcessCount() + ", Threads: " + os.getThreadCount());// Sort by highest CPUList<OSProcess> procs = Arrays.asList(os.getProcesses(5, ProcessSort.CPU));System.out.println("   PID  %CPU %MEM       VSZ       RSS Name");for (int i = 0; i < procs.size() && i < 5; i++) {OSProcess p = procs.get(i);System.out.format(" %5d %5.1f %4.1f %9s %9s %s%n", p.getProcessID(),100d * (p.getKernelTime() + p.getUserTime()) / p.getUpTime(),100d * p.getResidentSetSize() / memory.getTotal(), FormatUtil.formatBytes(p.getVirtualSize()),FormatUtil.formatBytes(p.getResidentSetSize()), p.getName());}}private static void printSensors(Sensors sensors) {System.out.println("Sensors:");System.out.format(" CPU Temperature: %.1f°C%n", sensors.getCpuTemperature());System.out.println(" Fan Speeds: " + Arrays.toString(sensors.getFanSpeeds()));System.out.format(" CPU Voltage: %.1fV%n", sensors.getCpuVoltage());}private static void printPowerSources(PowerSource[] powerSources) {StringBuilder sb = new StringBuilder("Power: ");if (powerSources.length == 0) {sb.append("Unknown");} else {double timeRemaining = powerSources[0].getTimeRemaining();if (timeRemaining < -1d) {sb.append("Charging");} else if (timeRemaining < 0d) {sb.append("Calculating time remaining");} else {sb.append(String.format("%d:%02d remaining", (int) (timeRemaining / 3600),(int) (timeRemaining / 60) % 60));}}for (PowerSource pSource : powerSources) {sb.append(String.format("%n %s @ %.1f%%", pSource.getName(), pSource.getRemainingCapacity() * 100d));}System.out.println(sb.toString());}private static void printDisks(HWDiskStore[] diskStores) {System.out.println("Disks:");for (HWDiskStore disk : diskStores) {boolean readwrite = disk.getReads() > 0 || disk.getWrites() > 0;System.out.format(" %s: (model: %s - S/N: %s) size: %s, reads: %s (%s), writes: %s (%s), xfer: %s ms%n",disk.getName(), disk.getModel(), disk.getSerial(),disk.getSize() > 0 ? FormatUtil.formatBytesDecimal(disk.getSize()) : "?",readwrite ? disk.getReads() : "?", readwrite ? FormatUtil.formatBytes(disk.getReadBytes()) : "?",readwrite ? disk.getWrites() : "?", readwrite ? FormatUtil.formatBytes(disk.getWriteBytes()) : "?",readwrite ? disk.getTransferTime() : "?");HWPartition[] partitions = disk.getPartitions();if (partitions == null) {// TODO Remove when all OS's implementedcontinue;}for (HWPartition part : partitions) {System.out.format(" |-- %s: %s (%s) Maj:Min=%d:%d, size: %s%s%n", part.getIdentification(),part.getName(), part.getType(), part.getMajor(), part.getMinor(),FormatUtil.formatBytesDecimal(part.getSize()),part.getMountPoint().isEmpty() ? "" : " @ " + part.getMountPoint());}}}private static void printFileSystem(FileSystem fileSystem) {System.out.println("File System:");System.out.format(" File Descriptors: %d/%d%n", fileSystem.getOpenFileDescriptors(),fileSystem.getMaxFileDescriptors());OSFileStore[] fsArray = fileSystem.getFileStores();for (OSFileStore fs : fsArray) {long usable = fs.getUsableSpace();long total = fs.getTotalSpace();System.out.format(" %s (%s) [%s] %s of %s free (%.1f%%) is %s "+ (fs.getLogicalVolume() != null && fs.getLogicalVolume().length() > 0 ? "[%s]" : "%s")+ " and is mounted at %s%n",fs.getName(), fs.getDescription().isEmpty() ? "file system" : fs.getDescription(), fs.getType(),FormatUtil.formatBytes(usable), FormatUtil.formatBytes(fs.getTotalSpace()), 100d * usable / total,fs.getVolume(), fs.getLogicalVolume(), fs.getMount());}}private static void printNetworkInterfaces(NetworkIF[] networkIFs) {System.out.println("Network interfaces:");for (NetworkIF net : networkIFs) {System.out.format(" Name: %s (%s)%n", net.getName(), net.getDisplayName());System.out.format("   MAC Address: %s %n", net.getMacaddr());System.out.format("   MTU: %s, Speed: %s %n", net.getMTU(), FormatUtil.formatValue(net.getSpeed(), "bps"));System.out.format("   IPv4: %s %n", Arrays.toString(net.getIPv4addr()));System.out.format("   IPv6: %s %n", Arrays.toString(net.getIPv6addr()));boolean hasData = net.getBytesRecv() > 0 || net.getBytesSent() > 0 || net.getPacketsRecv() > 0|| net.getPacketsSent() > 0;System.out.format("   Traffic: received %s/%s%s; transmitted %s/%s%s %n",hasData ? net.getPacketsRecv() + " packets" : "?",hasData ? FormatUtil.formatBytes(net.getBytesRecv()) : "?",hasData ? " (" + net.getInErrors() + " err)" : "",hasData ? net.getPacketsSent() + " packets" : "?",hasData ? FormatUtil.formatBytes(net.getBytesSent()) : "?",hasData ? " (" + net.getOutErrors() + " err)" : "");}}private static void printNetworkParameters(NetworkParams networkParams) {System.out.println("Network parameters:");System.out.format(" Host name: %s%n", networkParams.getHostName());System.out.format(" Domain name: %s%n", networkParams.getDomainName());System.out.format(" DNS servers: %s%n", Arrays.toString(networkParams.getDnsServers()));System.out.format(" IPv4 Gateway: %s%n", networkParams.getIpv4DefaultGateway());System.out.format(" IPv6 Gateway: %s%n", networkParams.getIpv6DefaultGateway());}private static void printDisplays(Display[] displays) {System.out.println("Displays:");int i = 0;for (Display display : displays) {System.out.println(" Display " + i + ":");System.out.println(display.toString());i++;}}private static void printUsbDevices(UsbDevice[] usbDevices) {System.out.println("USB Devices:");for (UsbDevice usbDevice : usbDevices) {System.out.println(usbDevice.toString());}}
}

运行结果:

代码连接:

Java获取计算机各类信息的方法(磁盘,系统,内存等等信息)相关推荐

  1. java获取计算机cpu利用率和内存使用信息

    利用java获取计算机cpu利用率和内存使用信息 1.pojo类: public class MonitorInfoBean {     /** 可使用内存. */     private long ...

  2. Java 查看文件绝对路径,JAVA获取文件绝对路径的方法

    本文实例讲述了JAVA获取文件绝对路径的方法.分享给大家供大家参考.具体实现方法如下: /** * 获取一个类的class文件所在的绝对路径. 这个类可以是JDK自身的类,也可以是用户自定义的类,或者 ...

  3. java获取文件名方法,利用Java获取文件名、类名、方法名和行号的方法小结

    大家都知道,在C语言中,我们可以通过宏FILE. __LINE__来获取文件名和行号,而在Java语言中,则可以通过StackTraceElement类来获取文件名.类名.方法名.行号,具体代码如下: ...

  4. java 根据日期获取天数,java获取日期之间天数的方法

    java获取日期之间天数的方法 本文实例讲述了java获取日期之间天数的方法.分享给大家供大家参考.具体实现方法如下: private int daysBetween(Date now, Date r ...

  5. Java获取当前时间年月日的方法

    Java获取当前时间年月日的方法 public static void main(String[] args) throws ParseException {Calendar now = Calend ...

  6. java 字符串截取的几种方式 java获取当前路径的几种方法

    java 字符串截取的几种方式: https://blog.csdn.net/qq_27603235/article/details/51604584 java获取当前路径的几种方法: https:/ ...

  7. java 获取时间戳 的三种方法

    java 获取时间戳 的三种方法,效率依次递减 方法一 : System.currentTimeMillis(); 方法二: new Date().getTime(); 方法三: Calendar.g ...

  8. mysql实现vpd_一种存储的VPD信息访问方法及系统与流程

    本发明涉及计算机存储技术领域,具体地说是一种存储的VPD信息访问方法及系统. 背景技术: 随着存储设备的快速发展,中高端存储逐渐受到更多用户的青睐,同时中高端存储面对着越来越多的存储设备属性信息,如何 ...

  9. python获取系统内存占用信息的实例方法

    psutil是一个跨平台库(http://code.google.com/p/psutil/),能够轻松实现获取系统运行的进程和系统利用率(包括CPU.内存.磁盘.网络等)信息.它主要应用于系统监控, ...

  10. 0基础搭建Prometheus+Grafana监控服务器CPU、磁盘、内存等信息

    这里写自定义目录标题 0基础搭建Prometheus+Grafana监控服务器CPU.磁盘.内存等信息 1.实验环境准备 2.基础环境配置 3.部署prometheus 4.部署Grafana可视化图 ...

最新文章

  1. C标准库和glibc(C运行库)的关系
  2. springboot 拦截器 日志_跟武哥一起学习Spring Boot,一份全面详细的学习教程
  3. 电感是怎么储存能量的
  4. Google怎么做(1.相关提示)
  5. linux限制单个用户使用,linux下限制用户使用系统资源
  6. Castle ActiveRecord学习实践(7):使用HQL查询
  7. 呼叫中心基层管理的目标和原则方法细分
  8. 苹果mac预览应用使用方法
  9. STL 格式解析--文本以及二进制格式
  10. 微信公众号菜单html5,微信公众号自定义菜单全攻略
  11. 禅道页面无法正常打开
  12. 【小5聊】移动开发性能优化解决卡顿眩晕问题提高用户体验
  13. 如何用QGIS 3.22将遥感影像切割成小矩形图片(机器学习数据)
  14. APP多平台快速切换
  15. Linux编程入门四进程
  16. iPhone的地图app如何获取任意地点的路线
  17. 冯唐:年轻人到底挣多少钱算够?
  18. JS -- 模块化(babel转译工具)
  19. 高等教育学:学生与教师
  20. 爬虫之极验验证码破解-滑动拼图验证码破解

热门文章

  1. 56. mysqli 扩展库(3)
  2. 9. Document getElementsByName() 方法
  3. Java中的HashCode 1 之hash算法基本原理
  4. Linux实战教学笔记01:计算机硬件组成与基本原理
  5. python yiled
  6. php : 开发记录(2017-03-10)
  7. 创建maven工程时总是带有后缀名Maven Webapp解决办法
  8. 给Debian浏览器安装flash播放插件
  9. 嵌入式linux环境搭建
  10. spellcheck 属性 html5的新属性,对元素内容进行拼写检查