Javaを使ってシステム情報を取得するための常用コード整理まとめ


1.CPUとメモリ情報を取得する

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;
/**
 *   windows    (CPU,  ,    )
 * @author libing
 *
 */
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());
 }
 //       
 public static String getMemery(){
 OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
 //       +    
 long totalvirtualMemory = osmxb.getTotalSwapSpaceSize();
 //        
 long freePhysicalMemorySize = osmxb.getFreePhysicalMemorySize();
 Double compare=(Double)(1-freePhysicalMemorySize*1.0/totalvirtualMemory)*100;
 String str="     :"+compare.intValue()+"%";
 return str;
 }
 //         
 public static List<String> getDisk() {
 //     
 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+":      "+compare.intValue()+"%";
     list.add(str);
     }
   }
    return list;
 }
 //  cpu   
 public static String getCpuRatioForWindows() {
     try {
       String procCmd = System.getenv("windir") + "//system32//wbem//wmic.exe process get Caption,CommandLine,KernelModeTime,ReadOperationCount,ThreadCount,UserModeTime,WriteOperationCount";
       //      
       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   :"+Double.valueOf(PERCENT * (busytime)*1.0 / (busytime + idletime)).intValue()+"%";
       } else {
         return "CPU   :"+0+"%";
       }
     } catch (Exception ex) {
       ex.printStackTrace();
       return "CPU   :"+0+"%";
     }
   }
 //  cpu    
  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;
        }
        //       :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;
  }
  /**
  *   String.subString         (           ),                 ,     :
  * @param src        
  * @param start_idx     (     )
  * @param end_idx     (     )
  * @return
  */
  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.本機のIPアドレスを取得する:

private static String getIpAddress() throws UnknownHostException { 
    InetAddress address = InetAddress.getLocalHost(); 
 
    return address.getHostAddress(); 
  }
 
3.インターネットカードの住所を取得する

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; 
 
  } 

4.オペレーティングシステムのアカウントを取得する

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

5.オペレーティングシステムのバージョンを取得する

import java.util.Properties;  
   
Properties props=System.getProperties(); //         
String osName = props.getProperty("os.name"); //        
String osArch = props.getProperty("os.arch"); //        
String osVersion = props.getProperty("os.version"); //      
   
6.よく使う情報の入手方法の整理
java.version    Java実行時の環境バージョン 
java.ventdor     Java実行時の環境サプライヤー 
java.ventdor.url     JavaサプライヤーのURL 
java.home   Javaインストールディレクトリ 
java.vm.specification.version   Java仮想マシン標準バージョン 
java.vm.specification.ventdor    Java仮想マシン規範サプライヤー 
java.vm.specification.name  Java仮想マシン仕様名 
java.vm.version     Java仮想マシンのバージョンを実現 
java.vm.ventdor  Java仮想マシン実現サプライヤー 
java.vm.name    Java仮想マシンの名前を実現します。 
java.specification.version  Java実行時の環境規範バージョン 
java.specification.ventdor   Java実行時の環境規範サプライヤー 
java.specification.name     Java実行時の環境規範名 
java.class.version  Javaクラスのフォーマットのバージョン番号 
java.class.path     Javaクラスのパス 
java.library.path   ライブラリを読み込み中に検索したパスのリスト 
java.io.tmpdir  デフォルトの一時ファイルパス 
java.com mpiler   使用するJITコンパイラの名前 
java.ext.dirs   1つ以上の拡張ディレクトリのパス 
os.name     オペレーティングシステムの名前 
オズ.arch     オペレーティングシステムのアーキテクチャ 
os.version  オペレーティングシステムのバージョン 
file.separator  ファイルセパレータ(UNIXシステムでは/) 
path.separator  パスセパレータ(UNIXシステムでは「:」) 
ライン.separator  行区切り記号(UNIXシステムでは「/n」) 
user.name   ユーザのアカウント名 
user.home   ユーザのホームディレクトリ 
アメリカ.dir    ユーザの現在の作業ディレクトリ