Use Java to obtain the system information of the common code collation summary

  • 2020-04-01 04:23:32
  • OfStack

1. Get CPU and memory information


import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.ArrayList;
import java.util.List;
import mytools.com.sun.management.OperatingSystemMXBean;
import mytools.java.io.File;
import mytools.java.lang.management.ManagementFactory;

public class WindowsInfoUtil {
  private static final int CPUTIME = 500;
  private static final int PERCENT = 100;
  private static final int FAULTLENGTH = 10;
  public static void main(String[] args) {
  System.out.println(getCpuRatioForWindows());
  System.out.println(getMemery());
  System.out.println(getDisk());
 }
 //Get memory usage
 public static String getMemery(){
 OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
 //Total physical memory + virtual memory
 long totalvirtualMemory = osmxb.getTotalSwapSpaceSize();
 //The remaining physical memory
 long freePhysicalMemorySize = osmxb.getFreePhysicalMemorySize();
 Double compare=(Double)(1-freePhysicalMemorySize*1.0/totalvirtualMemory)*100;
 String str=" Memory used :"+compare.intValue()+"%";
 return str;
 }
 //Gets file system usage
 public static List<String> getDisk() {
 //The operating system
 List<String> list=new ArrayList<String>();
 for (char c = 'A'; c <= 'Z'; c++) {
  String dirName = c + ":/";
  File win = new File(dirName);
     if(win.exists()){
     long total=(long)win.getTotalSpace();
     long free=(long)win.getFreeSpace();
     Double compare=(Double)(1-free*1.0/total)*100;
     String str=c+": disc   Has been used  "+compare.intValue()+"%";
     list.add(str);
     }
   }
    return list;
 }
 //Gain CPU usage
 public static String getCpuRatioForWindows() {
     try {
       String procCmd = System.getenv("windir") + "//system32//wbem//wmic.exe process get Caption,CommandLine,KernelModeTime,ReadOperationCount,ThreadCount,UserModeTime,WriteOperationCount";
       //Fetch process information
       long[] c0 = readCpu(Runtime.getRuntime().exec(procCmd));
       Thread.sleep(CPUTIME);
       long[] c1 = readCpu(Runtime.getRuntime().exec(procCmd));
       if (c0 != null && c1 != null) {
         long idletime = c1[0] - c0[0];
         long busytime = c1[1] - c0[1];
         return "CPU usage :"+Double.valueOf(PERCENT * (busytime)*1.0 / (busytime + idletime)).intValue()+"%";
       } else {
         return "CPU usage :"+0+"%";
       }
     } catch (Exception ex) {
       ex.printStackTrace();
       return "CPU usage :"+0+"%";
     }
   }
 //Read cpu-related information
  private static long[] readCpu(final Process proc) {
    long[] retn = new long[2];
    try {
      proc.getOutputStream().close();
      InputStreamReader ir = new InputStreamReader(proc.getInputStream());
      LineNumberReader input = new LineNumberReader(ir);
      String line = input.readLine();
      if (line == null || line.length() < FAULTLENGTH) {
        return null;
      }
      int capidx = line.indexOf("Caption");
      int cmdidx = line.indexOf("CommandLine");
      int rocidx = line.indexOf("ReadOperationCount");
      int umtidx = line.indexOf("UserModeTime");
      int kmtidx = line.indexOf("KernelModeTime");
      int wocidx = line.indexOf("WriteOperationCount");
      long idletime = 0;
      long kneltime = 0;
      long usertime = 0;
      while ((line = input.readLine()) != null) {
        if (line.length() < wocidx) {
          continue;
        }
        //Field appears order: Caption, CommandLine KernelModeTime, ReadOperationCount,
        // ThreadCount,UserModeTime,WriteOperation
        String caption =substring(line, capidx, cmdidx - 1).trim();
        String cmd = substring(line, cmdidx, kmtidx - 1).trim();
        if (cmd.indexOf("wmic.exe") >= 0) {
          continue;
        }
        String s1 = substring(line, kmtidx, rocidx - 1).trim();
        String s2 = substring(line, umtidx, wocidx - 1).trim();
        if (caption.equals("System Idle Process") || caption.equals("System")) {
          if (s1.length() > 0)
            idletime += Long.valueOf(s1).longValue();
          if (s2.length() > 0)
            idletime += Long.valueOf(s2).longValue();
          continue;
        }
        if (s1.length() > 0)
          kneltime += Long.valueOf(s1).longValue();
        if (s2.length() > 0)
          usertime += Long.valueOf(s2).longValue();
      }
      retn[0] = idletime;
      retn[1] = kneltime + usertime;
      return retn;
    } catch (Exception ex) {
      ex.printStackTrace();
    } finally {
      try {
        proc.getInputStream().close();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    return null;
  }
  
  private static String substring(String src, int start_idx, int end_idx) {
  byte[] b = src.getBytes();
  String tgt = "";
  for (int i = start_idx; i <= end_idx; i++) {
  tgt += (char) b[i];
  }
  return tgt;
 }
}

2. Get the IP address of the machine:


private static String getIpAddress() throws UnknownHostException { 
    InetAddress address = InetAddress.getLocalHost(); 
 
    return address.getHostAddress(); 
  }

 
3. Get the network card address


public static String getMACAddress(){ 
 
    String address = ""; 
 
    String os = System.getProperty("os.name"); 
    String osUser=System.getProperty("user.name"); 
    if (os != null && os.startsWith("Windows")) { 
 
      try { 
 
        String command = "cmd.exe /c ipconfig /all"; 
         
        Process p = Runtime.getRuntime().exec(command); 
 
        BufferedReader br =new BufferedReader(new InputStreamReader(p.getInputStream())); 
 
        String line; 
 
        while ((line = br.readLine()) != null) { 
 
          if (line.indexOf("Physical Address") > 0) { 
 
            int index = line.indexOf(":"); 
 
            index += 2; 
 
            address = line.substring(index); 
 
            break; 
 
          } 
 
        } 
 
        br.close(); 
 
        return address.trim(); 
 
      } 
 
      catch (IOException e) { 
      } 
 
    } 
    return address; 
 
  } 

Get an operating system account


String osUser=System.getProperty("user.name"); 

5. Get the operating system version


import java.util.Properties;  
   
Properties props=System.getProperties(); //Gets the set of system properties
String osName = props.getProperty("os.name"); //Operating system name
String osArch = props.getProperty("os.arch"); //Operating system architecture
String osVersion = props.getProperty("os.version"); //Operating system version

     
6. Some commonly used information acquisition methods are sorted out

Java. Version      Java runtime environment version  
Java. Vendor        Java runtime environment vendor  
Java. Vendor. Url        Java vendor's URL 
Java. Home    Java installation directory  
Java. Vm. Specification. Version    Java virtual machine specification version  
Java. Vm. Specification. Vendor      Java virtual machine specification vendor  
Java. Vm. Specification. Name  Java virtual machine specification name  
Java vm. Version        Java virtual machine implementation version  
Java vm. Vendor  Java virtual machine implementation vendor  
Java vm. Name      Java virtual machine implementation name  
Java. Specification. Version  Java runtime environment specification version  
Java. Specification. Vendor    Java runtime environment specification vendor  
Java. Specification. Name        Java runtime environment specification name  
Java.class. Version  Java class format version number  
Java.class. Path        Java classpath  
Java library. Path    List of paths searched when loading the library  
Java. IO. Tmpdir  Default temporary file path  
Java.com piler    The name of the JIT compiler to use  
Java. Ext dirs    The path of one or more extended directories  
OS. Name        The name of the operating system  
OS. Arch        Operating system architecture  
OS. Version  Version of the operating system  
File. Separator  The file separator (in UNIX systems, "/")  
Path. Separator  Path separator (" : "in UNIX systems)  
Line. Separator  Line separators (" /n "in UNIX systems)  
User. Name    User's account name  
User. Home    User's home directory  
User. Dir      User's current working directory  


Related articles: