Javaはどのようにシステムcpu、メモリ、ハードディスクの情報を取得します

25399 ワード

1概要
この間、Javaでどのようにシステム情報を取得するかを模索しました.cpu、メモリ、ハードディスク情報などが含まれています.Javaが持参したパケットを使用して取得し始めましたが、このように取得したメモリ情報が正確ではなく、対応するパケットが見つからないなどのエラーが発生しやすいので、sigarプラグインを使用して取得します.以下では,この2つの方式でシステム情報を取得する方式とコードを列挙する.
2 Javaパッケージを使用してシステム情報を取得する
2.1 Javaパッケージを使用してシステム情報コードを取得するには、次のようにします.
2.1.1 Bytes.java
public class Bytes {public 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.1.2 IMonitorService.java
public interface IMonitorService {public MonitorInfoBean getMonitorInfoBean() throws Exception;}
2.1.3 MonitorInfoBean.java
public class MonitorInfoBean {private long totalMemory;private long freeMemory;private long maxMemory;private String osName;private long totalMemorySize;private long freePhysicalMemorySize;private long usedMemory;private int totalThread;private double cpuRatio;
public long getFreeMemory() {
    return freeMemory;
}

public void setFreeMemory(long freeMemory) {
    this.freeMemory = freeMemory;
}

public long getFreePhysicalMemorySize() {
    return freePhysicalMemorySize;
}

public void setFreePhysicalMemorySize(long freePhysicalMemorySize) {
    this.freePhysicalMemorySize = freePhysicalMemorySize;
}

public long getMaxMemory() {
    return maxMemory;
}

public void setMaxMemory(long maxMemory) {
    this.maxMemory = maxMemory;
}

public String getOsName() {
    return osName;
}

public void setOsName(String osName) {
    this.osName = osName;
}

public long getTotalMemory() {
    return totalMemory;
}

public void setTotalMemory(long totalMemory) {
    this.totalMemory = totalMemory;
}

public long getTotalMemorySize() {
    return totalMemorySize;
}

public void setTotalMemorySize(long totalMemorySize) {
    this.totalMemorySize = totalMemorySize;
}

public int getTotalThread() {
    return totalThread;
}

public void setTotalThread(int totalThread) {
    this.totalThread = totalThread;
}

public long getUsedMemory() {
    return usedMemory;
}

public void setUsedMemory(long usedMemory) {
    this.usedMemory = usedMemory;
}

public double getCpuRatio() {
    return cpuRatio;
}

public void setCpuRatio(double cpuRatio) {
    this.cpuRatio = cpuRatio;
}

}2.1.4
import java.io.InputStreamReader;import java.io.LineNumberReader;
//import sun.management.ManagementFactory;//import com.sun.management.OperatingSystemMXBean;import java.io.*;import java.lang.management.ManagementFactory;import java.util.StringTokenizer;
public class MonitorServiceImpl implements IMonitorService {private static final int CPUTIME = 30;private static final int PERCENT = 100;private static final int FAULTLENGTH = 10;private static final File versionFile = new File("/proc/version");private static String linuxVersion = null;
public MonitorInfoBean getMonitorInfoBean() throws Exception {
    int kb = 1024;
    long totalMemory = Runtime.getRuntime().totalMemory() / kb;
    long freeMemory = Runtime.getRuntime().freeMemory() / kb;
    long maxMemory = Runtime.getRuntime().maxMemory() / kb;

    // OperatingSystemMXBean osmxb = (OperatingSystemMXBean)
    // ManagementFactory
    // .getOperatingSystemMXBean();
    // String osName = System.getProperty("os.name");
    // long totalMemorySize = osmxb.getTotalPhysicalMemorySize() / kb;
    // long freePhysicalMemorySize = osmxb.getFreePhysicalMemorySize() / kb;
    // long usedMemory = (osmxb.getTotalPhysicalMemorySize() - osmxb
    // .getFreePhysicalMemorySize()) / kb;

    ThreadGroup parentThread;
    for (parentThread = Thread.currentThread().getThreadGroup(); parentThread.getParent() != null; parentThread = parentThread.getParent());
    int totalThread = parentThread.activeCount();
    double cpuRatio = 0;

    // if (osName.toLowerCase().startsWith("windows")) {
    // cpuRatio = this.getCpuRatioForWindows();
    // } else {
    // cpuRatio = this.getCpuRateForLinux();
    // }

    MonitorInfoBean infoBean = new MonitorInfoBean();
    infoBean.setFreeMemory(freeMemory);
    // infoBean.setFreePhysicalMemorySize(freePhysicalMemorySize);
    infoBean.setMaxMemory(maxMemory);
    // infoBean.setOsName(osName);
    infoBean.setTotalMemory(totalMemory);
    // infoBean.setTotalMemorySize(totalMemorySize);
    infoBean.setTotalThread(totalThread);
    // infoBean.setUsedMemory(usedMemory);
    infoBean.setCpuRatio(cpuRatio);
    return infoBean;
}

private static double getCpuRateForLinux() {
    InputStream is = null;
    InputStreamReader isr = null;
    BufferedReader brStat = null;
    StringTokenizer tokenStat = null;
    try {

        System.out.println("Get usage rate of CUP , linux version: " + linuxVersion);

        Process process = Runtime.getRuntime().exec("top -b -n 1");
        is = process.getInputStream();
        isr = new InputStreamReader(is);
        brStat = new BufferedReader(isr);

        if (linuxVersion.equals("2.4")) {
            brStat.readLine();
            brStat.readLine();
            brStat.readLine();
            brStat.readLine();
            tokenStat = new StringTokenizer(brStat.readLine());
            tokenStat.nextToken();
            tokenStat.nextToken();

            String user = tokenStat.nextToken();

            tokenStat.nextToken();
            String system = tokenStat.nextToken();
            tokenStat.nextToken();
            String nice = tokenStat.nextToken();
            System.out.println(user + " , " + system + " , " + nice);
            user = user.substring(0, user.indexOf("%"));
            system = system.substring(0, system.indexOf("%"));
            nice = nice.substring(0, nice.indexOf("%"));
            float userUsage = new Float(user).floatValue();
            float systemUsage = new Float(system).floatValue();
            float niceUsage = new Float(nice).floatValue();

            return (userUsage + systemUsage + niceUsage) / 100;

        } else {
            brStat.readLine();
            brStat.readLine();
            tokenStat = new StringTokenizer(brStat.readLine());
            tokenStat.nextToken();
            tokenStat.nextToken();
            tokenStat.nextToken();
            tokenStat.nextToken();
            tokenStat.nextToken();
            tokenStat.nextToken();
            tokenStat.nextToken();
            String cpuUsage = tokenStat.nextToken();
            System.out.println("CPU idle : " + cpuUsage);
            Float usage = new Float(cpuUsage.substring(0, cpuUsage.indexOf("%")));
            return (1 - usage.floatValue() / 100);
        }
    } catch (IOException ioe) {
        System.out.println(ioe.getMessage());
        freeResource(is, isr, brStat);
        return 1;
    } finally {
        freeResource(is, isr, brStat);
    }
}

private static void freeResource(InputStream is, InputStreamReader isr, BufferedReader br) {
    try {
        if (is != null)
            is.close();
        if (isr != null)
            isr.close();
        if (br != null)
            br.close();
    } catch (IOException ioe) {
        System.out.println(ioe.getMessage());
    }
}

private double 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 Double.valueOf(
                    PERCENT * (busytime) / (busytime + idletime)).doubleValue();
        } else {
            return 0.0;
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        return 0.0;
    }
}

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

            String caption = Bytes.substring(line, capidx, cmdidx - 1) .trim();
            String cmd = Bytes.substring(line, cmdidx, kmtidx - 1).trim();
            if (cmd.indexOf("wmic.exe") >= 0) {
                continue;
            }

            // log.info("line="+line);
            if (caption.equals("System Idle Process") || caption.equals("System")) {
                idletime += Long.valueOf(
                        Bytes.substring(line, kmtidx, rocidx - 1).trim()).longValue();
                idletime += Long.valueOf(
                        Bytes.substring(line, umtidx, wocidx - 1).trim()).longValue();
                continue;
            }

            kneltime += Long.valueOf(
                    Bytes.substring(line, kmtidx, rocidx - 1).trim()).longValue();
            usertime += Long.valueOf(
                    Bytes.substring(line, umtidx, wocidx - 1).trim()).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;
}

public static void main(String[] args) throws Exception {
    IMonitorService service = new MonitorServiceImpl();
    MonitorInfoBean monitorInfo = service.getMonitorInfoBean();
    System.out.println("cpu percent: " + monitorInfo.getCpuRatio());
    System.out.println("can use memory: " + monitorInfo.getTotalMemory());
    System.out.println("ideal memory: " + monitorInfo.getFreeMemory());
    System.out.println("largest memory: " + monitorInfo.getMaxMemory());
    System.out.println("all memory: " + monitorInfo.getTotalMemorySize() + "kb");
    System.out.println("ideal memory: " + monitorInfo.getFreeMemory() + "kb");
    System.out.println("used memory: " + monitorInfo.getUsedMemory() + "kb");
    System.out.println("thread num: " + monitorInfo.getTotalThread() + "kb");
}

}2.2実行結果を下図に示す.
3 sigarを用いてシステム情報を取得する
3.1インストールsigar-1.6.4.zipをダウンロードする
  java          ,      ,           ,      sigar      。   

    :http://sourceforge.net/projects/sigar/files/latest/download?source=files

     , lib sigar.jar  eclipse CLASSPATH ,  sigar-x86-winnt.dll  Java bin    。

3.2コードは以下のように実現される.
import java.net.InetAddress;import java.net.UnknownHostException;import java.util.Map;import java.util.Properties;import org.hyperic.sigar.CpuInfo;import org.hyperic.sigar.CpuPerc;import org.hyperic.sigar.FileSystem;import org.hyperic.sigar.FileSystemUsage;import org.hyperic.sigar.Mem;import org.hyperic.sigar.NetFlags;import org.hyperic.sigar.NetInterfaceConfig;import org.hyperic.sigar.NetInterfaceStat;import org.hyperic.sigar.OperatingSystem;import org.hyperic.sigar.Sigar;import org.hyperic.sigar.SigarException;import org.hyperic.sigar.Swap;import org.hyperic.sigar.Who;
public class RuntimeTest{public static void main(String[]args){try{//System情報、jvmからproperty();System.out.println(「----------------------------------------------------------------------」);//cpu情報cpu();System.out.println(「---------------------------------------------------------------------------------------」);//メモリ情報memory();System.out.println(「-------------------------------------------------------------------------------------------------------------」);//オペレーティングシステム情報os;System.out.println("---------------------------------------");//ユーザ情報who();System.out.println("-------------------------");//ファイルシステム情報file();System.out.println("-------------------------");//ネットワーク情報net();System.out.println("-----------------------------------------------------");//イーサネット情報ethernet();System.out.println();"----------------------------------");} catch (Exception e1) {e1.printStackTrace();}}
private static void property() throws UnknownHostException {
    Runtime r = Runtime.getRuntime();
    Properties props = System.getProperties();
    InetAddress addr;
    addr = InetAddress.getLocalHost();
    String ip = addr.getHostAddress();
    Map map = System.getenv();
    String userName = map.get("USERNAME");//      
    String computerName = map.get("COMPUTERNAME");//       
    String userDomain = map.get("USERDOMAIN");//        
    System.out.println("   :    " + userName);
    System.out.println("    :    " + computerName);
    System.out.println("     :    " + userDomain);
    System.out.println("  ip  :    " + ip);
    System.out.println("     :    " + addr.getHostName());
    System.out.println("JVM        :    " + r.totalMemory());
    System.out.println("JVM         :    " + r.freeMemory());
    System.out.println("JVM          :    " + r.availableProcessors());
    System.out.println("Java       :    " + props.getProperty("java.version"));
    System.out.println("Java        :    " + props.getProperty("java.vendor"));
    System.out.println("Java    URL:    " + props.getProperty("java.vendor.url"));
    System.out.println("Java     :    " + props.getProperty("java.home"));
    System.out.println("Java        :    " + props.getProperty("java.vm.specification.version"));
    System.out.println("Java         :    " + props.getProperty("java.vm.specification.vendor"));
    System.out.println("Java        :    " + props.getProperty("java.vm.specification.name"));
    System.out.println("Java        :    " + props.getProperty("java.vm.version"));
    System.out.println("Java         :    " + props.getProperty("java.vm.vendor"));
    System.out.println("Java        :    " + props.getProperty("java.vm.name"));
    System.out.println("Java         :    " + props.getProperty("java.specification.version"));
    System.out.println("Java          :    " + props.getProperty("java.specification.vender"));
    System.out.println("Java         :    " + props.getProperty("java.specification.name"));
    System.out.println("Java       :    " + props.getProperty("java.class.version"));
    System.out.println("Java    :    " + props.getProperty("java.class.path"));
    System.out.println("           :    " + props.getProperty("java.library.path"));
    System.out.println("         :    " + props.getProperty("java.io.tmpdir"));
    System.out.println("            :    " + props.getProperty("java.ext.dirs"));
    System.out.println("       :    " + props.getProperty("os.name"));
    System.out.println("       :    " + props.getProperty("os.arch"));
    System.out.println("       :    " + props.getProperty("os.version"));
    System.out.println("     :    " + props.getProperty("file.separator"));
    System.out.println("     :    " + props.getProperty("path.separator"));
    System.out.println("    :    " + props.getProperty("line.separator"));
    System.out.println("       :    " + props.getProperty("user.name"));
    System.out.println("      :    " + props.getProperty("user.home"));
    System.out.println("         :    " + props.getProperty("user.dir"));
}

private static void memory() throws SigarException {
    Sigar sigar = new Sigar();
    Mem mem = sigar.getMem();
    //     
    System.out.println("    :    " + mem.getTotal() / 1024L + "K av");
    //        
    System.out.println("       :    " + mem.getUsed() / 1024L + "K used");
    //        
    System.out.println("       :    " + mem.getFree() / 1024L + "K free");
    Swap swap = sigar.getSwap();
    //      
    System.out.println("     :    " + swap.getTotal() / 1024L + "K av");
    //         
    System.out.println("        :    " + swap.getUsed() / 1024L + "K used");
    //         
    System.out.println("        :    " + swap.getFree() / 1024L + "K free");
}

private static void cpu() throws SigarException {
    Sigar sigar = new Sigar();
    CpuInfo infos[] = sigar.getCpuInfoList();
    CpuPerc cpuList[] = null;
    cpuList = sigar.getCpuPercList();
    for (int i = 0; i < infos.length; i++) {//      CPU   CPU   
        CpuInfo info = infos[i];
        System.out.println(" " + (i + 1) + " CPU  ");
        System.out.println("CPU   MHz:    " + info.getMhz());// CPU   MHz
        System.out.println("CPU   :    " + info.getVendor());//   CPU   , :Intel
        System.out.println("CPU  :    " + info.getModel());//   CPU   , :Celeron
        System.out.println("CPU    :    " + info.getCacheSize());//        
        printCpuPerc(cpuList[i]);
    }
}

private static void printCpuPerc(CpuPerc cpu) {
    System.out.println("CPU     :    " + CpuPerc.format(cpu.getUser()));//      
    System.out.println("CPU     :    " + CpuPerc.format(cpu.getSys()));//      
    System.out.println("CPU     :    " + CpuPerc.format(cpu.getWait()));//      
    System.out.println("CPU     :    " + CpuPerc.format(cpu.getNice()));//
    System.out.println("CPU     :    " + CpuPerc.format(cpu.getIdle()));//      
    System.out.println("CPU     :    " + CpuPerc.format(cpu.getCombined()));//      
}

private static void os() {
    OperatingSystem OS = OperatingSystem.getInstance();
    //          : 386、486、586 x86
    System.out.println("    :    " + OS.getArch());
    System.out.println("    CpuEndian():    " + OS.getCpuEndian());//
    System.out.println("    DataModel():    " + OS.getDataModel());//
    //     
    System.out.println("       :    " + OS.getDescription());
    //       
    // System.out.println("OS.getName():    " + OS.getName());
    // System.out.println("OS.getPatchLevel():    " + OS.getPatchLevel());//
    //        
    System.out.println("       :    " + OS.getVendor());
    //     
    System.out.println("        :    " + OS.getVendorCodeName());
    //       
    System.out.println("      :    " + OS.getVendorName());
    //         
    System.out.println("        :    " + OS.getVendorVersion());
    //         
    System.out.println("        :    " + OS.getVersion());
}

private static void who() throws SigarException {
    Sigar sigar = new Sigar();
    Who who[] = sigar.getWhoList();
    if (who != null && who.length > 0) {
        for (int i = 0; i < who.length; i++) {
            // System.out.println("            " + String.valueOf(i));
            Who _who = who[i];
            System.out.println("     :    " + _who.getDevice());
            System.out.println("  host:    " + _who.getHost());
            // System.out.println("getTime():    " + _who.getTime());
            //             
            System.out.println("            :    " + _who.getUser());
        }
    }
}

private static void file() throws Exception {
    Sigar sigar = new Sigar();
    FileSystem fslist[] = sigar.getFileSystemList();
    for (int i = 0; i < fslist.length; i++) {
        System.out.println("       " + i);
        FileSystem fs = fslist[i];
        //        
        System.out.println("    :    " + fs.getDevName());
        //        
        System.out.println("    :    " + fs.getDirName());
        System.out.println("    :    " + fs.getFlags());//
        //       ,   FAT32、NTFS
        System.out.println("    :    " + fs.getSysTypeName());
        //        ,      、  、       
        System.out.println("     :    " + fs.getTypeName());
        //       
        System.out.println("        :    " + fs.getType());
        FileSystemUsage usage = null;
        usage = sigar.getFileSystemUsage(fs.getDirName());
        switch (fs.getType()) {
        case 0: // TYPE_UNKNOWN :  
            break;
        case 1: // TYPE_NONE
            break;
        case 2: // TYPE_LOCAL_DISK :     
            //        
            System.out.println(fs.getDevName() + "   :    " + usage.getTotal() + "KB");
            //         
            System.out.println(fs.getDevName() + "    :    " + usage.getFree() + "KB");
            //         
            System.out.println(fs.getDevName() + "    :    " + usage.getAvail() + "KB");
            //          
            System.out.println(fs.getDevName() + "     :    " + usage.getUsed() + "KB");
            double usePercent = usage.getUsePercent() * 100D;
            //           
            System.out.println(fs.getDevName() + "      :    " + usePercent + "%");
            break;
        case 3:// TYPE_NETWORK :  
            break;
        case 4:// TYPE_RAM_DISK :  
            break;
        case 5:// TYPE_CDROM :  
            break;
        case 6:// TYPE_SWAP :    
            break;
        }
        System.out.println(fs.getDevName() + "  :    " + usage.getDiskReads());
        System.out.println(fs.getDevName() + "  :    " + usage.getDiskWrites());
    }
    return;
}

private static void net() throws Exception {
    Sigar sigar = new Sigar();
    String ifNames[] = sigar.getNetInterfaceList();
    for (int i = 0; i < ifNames.length; i++) {
        String name = ifNames[i];
        NetInterfaceConfig ifconfig = sigar.getNetInterfaceConfig(name);
        System.out.println("     :    " + name);//      
        System.out.println("IP  :    " + ifconfig.getAddress());// IP  
        System.out.println("    :    " + ifconfig.getNetmask());//     
        if ((ifconfig.getFlags() & 1L) <= 0L) {
            System.out.println("!IFF_UP...skipping getNetInterfaceStat");
            continue;
        }
        NetInterfaceStat ifstat = sigar.getNetInterfaceStat(name);
        System.out.println(name + "       :" + ifstat.getRxPackets());//        
        System.out.println(name + "       :" + ifstat.getTxPackets());//        
        System.out.println(name + "        :" + ifstat.getRxBytes());//         
        System.out.println(name + "       :" + ifstat.getTxBytes());//        
        System.out.println(name + "        :" + ifstat.getRxErrors());//         
        System.out.println(name + "          :" + ifstat.getTxErrors());//           
        System.out.println(name + "        :" + ifstat.getRxDropped());//         
        System.out.println(name + "        :" + ifstat.getTxDropped());//         
    }
}

private static void ethernet() throws SigarException {
    Sigar sigar = null;
    sigar = new Sigar();
    String[] ifaces = sigar.getNetInterfaceList();
    for (int i = 0; i < ifaces.length; i++) {
        NetInterfaceConfig cfg = sigar.getNetInterfaceConfig(ifaces[i]);
        if (NetFlags.LOOPBACK_ADDRESS.equals(cfg.getAddress()) || (cfg.getFlags() & NetFlags.IFF_LOOPBACK) != 0
                || NetFlags.NULL_HWADDR.equals(cfg.getHwaddr())) {
            continue;
        }
        System.out.println(cfg.getName() + "IP  :" + cfg.getAddress());// IP  
        System.out.println(cfg.getName() + "      :" + cfg.getBroadcast());//       
        System.out.println(cfg.getName() + "  MAC  :" + cfg.getHwaddr());//   MAC  
        System.out.println(cfg.getName() + "    :" + cfg.getNetmask());//     
        System.out.println(cfg.getName() + "      :" + cfg.getDescription());//       
        System.out.println(cfg.getName() + "    " + cfg.getType());//
    }
}

}
転載先:https://blog.51cto.com/13299037/2151776