51工具盒子

依楼听风雨
笑看云卷云舒,淡观潮起潮落

Java获取操作系统信息

Java获取操作系统信息 {#java获取操作系统信息}

Maven依赖 {#maven依赖}

<dependency>
    <groupId>com.github.oshi</groupId>
    <artifactId>oshi-core</artifactId>
    <version>5.8.6</version>
</dependency>
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.7.17</version>
</dependency>

代码 {#代码}

import cn.hutool.core.io.unit.DataUnit;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.StrUtil;
import cn.hutool.system.oshi.OshiUtil;
import oshi.hardware.*;

import java.text.DecimalFormat;
import java.util.List;
import java.util.concurrent.TimeUnit;


/**




* 
  @author: lhDream





* 
  @create: 2021-12-26 19:18
  \*\*/
  public class Test {



  public static void main(String[] args) throws Exception{
  GlobalMemory memory = OshiUtil.getMemory();


       <span class="hljs-type">HardwareAbstractionLayer</span> <span class="hljs-variable">hardware</span> <span class="hljs-operator">=</span> OshiUtil.getHardware();

       Console.log(<span class="hljs-string">"CPU: {}"</span>, OshiUtil.getProcessor().getProcessorIdentifier().getName());
       Console.log(<span class="hljs-string">"内存: {} "</span>, formatData(memory.getTotal()));
       List&lt;GraphicsCard&gt; graphicsCards = hardware.getGraphicsCards();
       graphicsCards.forEach(e-&gt;{
           Console.log(<span class="hljs-string">"显卡: {}"</span>, e.getName());
       });
       Console.log(<span class="hljs-string">"cpu使用率: {}"</span>,  getCpuRate());

       <span class="hljs-comment">//内容总量</span>
       <span class="hljs-type">long</span> <span class="hljs-variable">total</span> <span class="hljs-operator">=</span> memory.getTotal();
       <span class="hljs-comment">//剩余内存</span>
       <span class="hljs-type">long</span> <span class="hljs-variable">available</span> <span class="hljs-operator">=</span> memory.getAvailable();
       <span class="hljs-comment">//使用量</span>
       <span class="hljs-type">long</span> <span class="hljs-variable">used</span> <span class="hljs-operator">=</span> total - available;
       Console.log(<span class="hljs-string">"内存: {}/{},占用率率: {}"</span>,formatData(used),formatData(total),formatRate(used * <span class="hljs-number">1.0</span> / total));

       Console.log(<span class="hljs-string">"网络: {}"</span>,net());

       <span class="hljs-comment">//List&lt;UsbDevice&gt; usbDevices = hardware.getUsbDevices(false);</span>
       <span class="hljs-comment">//usbDevices.forEach(e-&gt;{</span>
       <span class="hljs-comment">//    Console.log("usb: {}",e.getName());</span>
       <span class="hljs-comment">//});</span>




  }


  /**
  *



  * @return cpuRate cpu使用率


  * @throws InterruptedException
    */
    public static String getCpuRate() throws InterruptedException {
    CentralProcessor processor = OshiUtil.getHardware().getProcessor();
    long[] prevTicks = processor.getSystemCpuLoadTicks();
    // 睡眠1s
    TimeUnit.SECONDS.sleep(1);
    long[] ticks = processor.getSystemCpuLoadTicks();
    long nice = ticks[CentralProcessor.TickType.NICE.getIndex()]
    - prevTicks[CentralProcessor.TickType.NICE.getIndex()];
    long irq = ticks[CentralProcessor.TickType.IRQ.getIndex()]
    - prevTicks[CentralProcessor.TickType.IRQ.getIndex()];
    long softirq = ticks[CentralProcessor.TickType.SOFTIRQ.getIndex()]
    - prevTicks[CentralProcessor.TickType.SOFTIRQ.getIndex()];
    long steal = ticks[CentralProcessor.TickType.STEAL.getIndex()]
    - prevTicks[CentralProcessor.TickType.STEAL.getIndex()];
    long cSys = ticks[CentralProcessor.TickType.SYSTEM.getIndex()]
    - prevTicks[CentralProcessor.TickType.SYSTEM.getIndex()];
    long user = ticks[CentralProcessor.TickType.USER.getIndex()]
    - prevTicks[CentralProcessor.TickType.USER.getIndex()];
    long iowait = ticks[CentralProcessor.TickType.IOWAIT.getIndex()]
    - prevTicks[CentralProcessor.TickType.IOWAIT.getIndex()];
    long idle = ticks[CentralProcessor.TickType.IDLE.getIndex()]
    - prevTicks[CentralProcessor.TickType.IDLE.getIndex()];
    long totalCpu = user + nice + cSys + idle + iowait + irq + softirq + steal;
    return new DecimalFormat("#.##%").format((cSys + user) * 1.0 / totalCpu);
    }




  public static String net() throws InterruptedException {
  HardwareAbstractionLayer hardware = OshiUtil.getHardware();
  List\<NetworkIF\> networkIFs = hardware.getNetworkIFs();


       <span class="hljs-type">long</span> <span class="hljs-variable">up</span> <span class="hljs-operator">=</span> <span class="hljs-number">0</span>;
       <span class="hljs-type">long</span> <span class="hljs-variable">down</span> <span class="hljs-operator">=</span><span class="hljs-number">0</span>;
       <span class="hljs-type">long</span> time=<span class="hljs-number">0</span>;

       <span class="hljs-keyword">for</span> (<span class="hljs-type">int</span> <span class="hljs-variable">i</span> <span class="hljs-operator">=</span> <span class="hljs-number">0</span>; i &lt; networkIFs.size(); i++) {
           <span class="hljs-type">NetworkIF</span> <span class="hljs-variable">net</span> <span class="hljs-operator">=</span> networkIFs.get(i);
           <span class="hljs-type">long</span> <span class="hljs-variable">bytesSent</span> <span class="hljs-operator">=</span> net.getBytesSent();
           <span class="hljs-type">long</span> <span class="hljs-variable">bytesRecv</span> <span class="hljs-operator">=</span> net.getBytesRecv();
           <span class="hljs-type">long</span> <span class="hljs-variable">timeStamp</span> <span class="hljs-operator">=</span> net.getTimeStamp();
           up += bytesSent;
           down += bytesRecv;
           time += timeStamp;
       }
       TimeUnit.SECONDS.sleep(<span class="hljs-number">1</span>);

       networkIFs = hardware.getNetworkIFs();
       <span class="hljs-type">long</span> <span class="hljs-variable">upload</span> <span class="hljs-operator">=</span> <span class="hljs-number">0</span>;
       <span class="hljs-type">long</span> <span class="hljs-variable">download</span> <span class="hljs-operator">=</span><span class="hljs-number">0</span>;
       <span class="hljs-type">long</span> time_=<span class="hljs-number">0</span>;
       <span class="hljs-keyword">for</span> (<span class="hljs-type">int</span> <span class="hljs-variable">i</span> <span class="hljs-operator">=</span> <span class="hljs-number">0</span>; i &lt; networkIFs.size(); i++) {
           <span class="hljs-type">NetworkIF</span> <span class="hljs-variable">net</span> <span class="hljs-operator">=</span> networkIFs.get(i);
           <span class="hljs-type">long</span> <span class="hljs-variable">bytesSent</span> <span class="hljs-operator">=</span> net.getBytesSent();
           <span class="hljs-type">long</span> <span class="hljs-variable">bytesRecv</span> <span class="hljs-operator">=</span> net.getBytesRecv();
           <span class="hljs-type">long</span> <span class="hljs-variable">timeStamp</span> <span class="hljs-operator">=</span> net.getTimeStamp();
           upload += bytesSent;
           download += bytesRecv;
           time_ += timeStamp;
       }

       <span class="hljs-type">String</span> <span class="hljs-variable">downloadStr</span> <span class="hljs-operator">=</span> formatData((download - down) / (time_ - time) * <span class="hljs-number">1000</span>)+<span class="hljs-string">"/s"</span>;
       <span class="hljs-type">String</span> <span class="hljs-variable">uploadStr</span> <span class="hljs-operator">=</span>formatData((upload - up) / (time_ - time) * <span class="hljs-number">1000</span>) + <span class="hljs-string">"/s"</span>;
       <span class="hljs-keyword">return</span> StrUtil.format(<span class="hljs-string">"↓: {} ↑: {}"</span>,downloadStr,uploadStr);




  }


  /**



  * 格式化输出百分比


  * @param rate


  * @return
    */
    public static String formatRate(double rate){
    return new DecimalFormat("#.##%").format(rate);
    }




  /**



  * 格式化输出大小 B/KB/MB...


  * @param size


  * @return
    */
    public static String formatData(long size) {
    if (size <= 0L) {
    return "0B";
    } else {
    int digitGroups = Math.min(DataUnit.UNIT_NAMES.length - 1, (int)(Math.log10((double)size) / Math.log10(1024.0D)));
    return (new DecimalFormat("#,##0.##")).format((double)size / Math.pow(1024.0D, (double)digitGroups)) + " " + DataUnit.UNIT_NAMES[digitGroups];
    }
    }





`}
`

效果 {#效果}

CPU: Intel(R) Core(TM) i5-6400 CPU @ 2.70GHz
内存: 15.93 GB 
显卡: NVIDIA GeForce GT 730
cpu使用率: 17.16%
内存: 8.52 GB/15.93 GB,占用率率: 53.46%
网络: ↓: 26.37 KB/s ↑: 4.88 KB/s
赞(1)
未经允许不得转载:工具盒子 » Java获取操作系统信息