• 获取系统相关信息 (CPU使用率 内存使用率 系统磁盘大小)


    引言

       在软件开个过程中,对于软件的稳定性和使用率也是我们需要关注的 。

     使用sigar来监控,简单方便!

     使用说明:下载sigar jar及配合sigar的dll文件来用,需要将dll文件放到JDK下的bin文件夹下,供sigar程序调用。以下程序经过测试,完全可用!
      1 package com.thinkgem.jeesite.common.utils;
      2 
      3 import java.io.File;
      4 import java.io.InputStreamReader;
      5 import java.io.LineNumberReader;
      6 import java.text.DecimalFormat;
      7 
      8 import javax.swing.filechooser.FileSystemView;
      9 
     10 import org.hyperic.sigar.Mem;
     11 import org.hyperic.sigar.Sigar;
     12 import org.hyperic.sigar.SigarException;
     13 
     14 /**
     15  * 
     16  *@description:功能说明:获取系统相关信息 (内存使用率 cpu使用率 磁盘大小及使用率)
     17  *@author:zsq
     18  *Creation date:2019年6月28日 下午3:24:39
     19  */
     20 public class SystemRelatedInfoUtils
     21 {
     22     private static final int CPUTIME=500;
     23   
     24     private static final int PERCENT=100;
     25   
     26     private static final int FAULTLENGTH=10;
     27     
     28     /** 
     29      * 获得系统时间.  
     30      * @return 获得系统时间. 
     31      * @author zsq     
     32      * Creation date: 2019年6月28日 下午3:30:39
     33      */  
     34     public static String getSystemDate(){
     35       String date=DateUtils.getDate();
     36       return "报告日期:"+date;
     37     } 
     38     
     39     
     40     /**
     41      * 获得CPU使用率.  
     42      * @return 返回cpu使用率  
     43      * @author amg     
     44      * Creation date: 2019年6月28日 下午3:35:39
     45      */  
     46     public static  String  getCpuRatioForWindows() {   
     47         try {
     48             String procCmd = System.getenv("windir")
     49               + "//system32//wbem//wmic.exe process get Caption,CommandLine,KernelModeTime,ReadOperationCount,ThreadCount,UserModeTime,WriteOperationCount";
     50             // 取进程信息
     51             long[] c0 = readCpu(Runtime.getRuntime().exec(procCmd));
     52             Thread.sleep(CPUTIME);
     53             long[] c1 = readCpu(Runtime.getRuntime().exec(procCmd));
     54             if (c0 != null && c1 != null) {
     55              long idletime = c1[0] - c0[0];
     56              long busytime = c1[1] - c0[1];
     57              return "CPU使用率:"
     58                + Double.valueOf(
     59                  PERCENT * (busytime) * 1.0
     60                    / (busytime + idletime)).intValue()
     61                + "%";
     62             } else {
     63              return "CPU使用率:" + 0 + "%";
     64             }
     65            } catch (Exception ex) {
     66             ex.printStackTrace();
     67             return "CPU使用率:" + 0 + "%";
     68            }
     69     }   
     70     
     71     /**
     72      * 读取CPU信息.  
     73      * @param proc  
     74      * @return  
     75      * @author amg    
     76      * Creation date: 2019年6月28日 下午3:40:39
     77      */  
     78     private static long[] readCpu(final Process proc) {   
     79         long[] retn = new long[2];
     80         try {
     81          proc.getOutputStream().close();
     82          InputStreamReader ir = new InputStreamReader(proc.getInputStream());
     83          LineNumberReader input = new LineNumberReader(ir);
     84          String line = input.readLine();
     85          if (line == null || line.length() < FAULTLENGTH) {
     86           return null;
     87          }
     88          int capidx = line.indexOf("Caption");
     89          int cmdidx = line.indexOf("CommandLine");
     90          int rocidx = line.indexOf("ReadOperationCount");
     91          int umtidx = line.indexOf("UserModeTime");
     92          int kmtidx = line.indexOf("KernelModeTime");
     93          int wocidx = line.indexOf("WriteOperationCount");
     94          long idletime = 0;
     95          long kneltime = 0;
     96          long usertime = 0;
     97          while ((line = input.readLine()) != null) {
     98           if (line.length() < wocidx) {
     99            continue;
    100           }
    101           // 字段出现顺序:Caption,CommandLine,KernelModeTime,ReadOperationCount,
    102           // ThreadCount,UserModeTime,WriteOperation
    103           String caption = substring(line, capidx, cmdidx - 1).trim();
    104           String cmd = substring(line, cmdidx, kmtidx - 1).trim();
    105           if (cmd.indexOf("wmic.exe") >= 0) {
    106            continue;
    107           }
    108           String s1 = substring(line, kmtidx, rocidx - 1).trim();
    109           String s2 = substring(line, umtidx, wocidx - 1).trim();
    110           if (caption.equals("System Idle Process")
    111             || caption.equals("System")) {
    112            if (s1.length() > 0)
    113             idletime += Long.valueOf(s1).longValue();
    114            if (s2.length() > 0)
    115             idletime += Long.valueOf(s2).longValue();
    116            continue;
    117           }
    118           if (s1.length() > 0)
    119            kneltime += Long.valueOf(s1).longValue();
    120           if (s2.length() > 0)
    121            usertime += Long.valueOf(s2).longValue();
    122          }
    123          
    124          retn[0] = idletime;
    125          retn[1] = kneltime + usertime;
    126          return retn;
    127         } catch (Exception ex) {
    128          ex.printStackTrace();
    129         } finally {
    130          try {
    131           proc.getInputStream().close();
    132          } catch (Exception e) {
    133           e.printStackTrace();
    134          }
    135         }
    136         return null;
    137     }  
    138     
    139      /** 
    140      * 由于String.subString对汉字处理存在问题(把一个汉字视为一个字节),因此在  
    141      * 包含汉字的字符串时存在隐患,现调整如下:  
    142      * @param src 要截取的字符串  
    143      * @param start_idx 开始坐标(包括该坐标)  
    144      * @param end_idx   截止坐标(包括该坐标)  
    145      * @return  
    146      */  
    147     public static String substring(String src, int start_idx, int end_idx){   
    148         byte[] b = src.getBytes();
    149         String tgt = "";
    150         for (int i = start_idx; i <= end_idx; i++) {
    151          tgt += (char) b[i];
    152         }
    153         return tgt;
    154     }  
    155     
    156     /** 
    157      * 获取内存使用率.  
    158      * @return 获得内存使用率. 
    159      * @author amg     
    160      * Creation date: 2019年6月28日 下午4:30:39
    161      */  
    162     @SuppressWarnings("unused")
    163     public static  String  getMemory() {
    164         Sigar sigar=new Sigar();
    165         Mem men;
    166         String string="";
    167         try
    168         {
    169             men = sigar.getMem();
    170             double total=men.getTotal()/1024;
    171             double use=men.getUsed()/1024;
    172             //double free=men.getFree()/1024;
    173             double rs=(use/total)*100;
    174             //内存总量
    175            // System.out.println("内存总量: "+total+" k av");
    176             //当前内存使用量  
    177            // System.out.println("当前内存使用量:  "+use+" k use");
    178             // 当前内存剩余量  
    179            // System.err.println("当前内存剩余量: "+free+" k free");
    180            // System.err.println("*****内存使用率: "+String.format("%.2f", rs)+"%");
    181            string="内存使用率: "+String.format("%.2f", rs)+"%";
    182         } catch (SigarException e)
    183         {
    184             e.printStackTrace();
    185         }
    186         return string;
    187     }
    188     
    189      /** 
    190      * 获取磁盘信息.  
    191      * @return 获取磁盘信息. 
    192      * @author amg     
    193      * Creation date: 2019年6月28日 下午4:40:39
    194      */  
    195     public static String  getDisk(){
    196         // 当前文件系统类
    197         FileSystemView fsv = FileSystemView.getFileSystemView();
    198         // 列出所有windows 磁盘
    199         File[] fs = File.listRoots();
    200         double totalSpace=0f;
    201         double freeSpace=0f;
    202         // 显示磁盘卷标
    203         for (int i = 0; i < fs.length; i++) {
    204             //System.out.println(fsv.getSystemDisplayName(fs[i]));
    205            // System.out.print("总大小" + FormetFileSize(fs[i].getTotalSpace()));
    206            // System.out.println("剩余" + FormetFileSize(fs[i].getFreeSpace()));
    207             totalSpace+=Double.valueOf(FormetFileSize(fs[i].getTotalSpace()));
    208             freeSpace+=Double.valueOf(FormetFileSize(fs[i].getFreeSpace()));    
    209         }
    210       
    211        // System.err.println("*****磁盘总大小: "+String.format("%.0f",totalSpace)+"G");
    212        // System.err.println("*****磁盘剩余: "+String.format("%.0f",freeSpace)+"G");
    213        String  totalSpaceStr="";
    214        String  freeSpaceStr="";
    215        //空间大于1024G就用T
    216         if(totalSpace>1024){
    217             totalSpace= totalSpace/1024;
    218             totalSpaceStr=String.format("%.2f",totalSpace)+"T";
    219         }else{
    220             totalSpaceStr=String.format("%.0f",totalSpace)+"G"; 
    221         }
    222         if(freeSpace>1024){
    223             freeSpace= freeSpace/1024;
    224             freeSpaceStr=String.format("%.2f",freeSpace)+"T";
    225         }else{
    226             freeSpaceStr=String.format("%.2f",freeSpace)+"G"; 
    227         }
    228         
    229         double rs=((totalSpace-freeSpace)/totalSpace)*100;
    230         String message="磁盘空间: 总大小"+totalSpaceStr+", 已用 "+String.format("%.2f",rs)+"%"+", 剩余:"+freeSpaceStr;
    231         return message;
    232     }
    233      /*
    234      * 格式化 计算出 M G T(磁盘大小)
    235      */
    236     public static String FormetFileSize(long fileS) {
    237         DecimalFormat df = new DecimalFormat("#.00");
    238         String fileSizeString = "";
    239         if (fileS < 1024) {
    240             fileSizeString = df.format((double) fileS);//B
    241         } else if (fileS < 1048576) {
    242             fileSizeString = df.format((double) fileS / 1024) ;//K
    243         } else if (fileS < 1073741824) {
    244             fileSizeString = df.format((double) fileS / 1048576);//M
    245         }else {
    246             fileSizeString = df.format((double) fileS / 1073741824);//G
    247         }
    248         
    249         return fileSizeString;
    250     }
    251    
    252     
    253    
    254     public static void main(String[] args) 
    255     {
    256         SystemRelatedInfoUtils srf=new SystemRelatedInfoUtils();
    257         long start=System.currentTimeMillis();
    258         System.out.println(getSystemDate());
    259         System.out.println(getCpuRatioForWindows());
    260         long end=System.currentTimeMillis();
    261         //System.out.println("用时:"+(end-start)/1000+"s");
    262         System.err.println(getMemory());
    263         System.err.println(getDisk());
    264     }
    265 }

    运行效果:

  • 相关阅读:
    【JLOI 2015】城池攻占
    【BalticOI 2004】Sequence
    罗马游戏
    《STL源码剖析》STL迭代器分类
    《Effective C++》模版与泛型编程
    《Effective C++》继承与面向对象设计
    《Effective C++》实现 章节
    [C++]const_cast,dynamic_cast,reinterpret_cast,static_cast转型
    [C++]default constructor默认构造函数
    [C++]union联合体总结
  • 原文地址:https://www.cnblogs.com/zhaosq/p/11103785.html
Copyright © 2020-2023  润新知