欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java采集主机数据

程序员文章站 2022-07-02 09:25:15
...

1 Sigar

使用java自带的包获取系统数据,容易找不到包,尤其是内存信息不够准确,所以选择使用sigar获取系统信息。

下载地址:http://sourceforge.net/projects/sigar/files/latest/download?source=files

Sigar(System Information Gatherer And Reporter,系统信息收集和报表工具) 是Hyperic-hq产品的基础包,是Hyperic HQ主要的数据收集组件。它用来从许多平台收集系统和处理信息. 这些平台包括:Linux, Windows, Solaris, AIX, HP-UX, FreeBSD and Mac OSX。Sigar有C,C#,Java和Perl API,java版的API为sigar.jar,sigar.jar的底层是用C语言编写的,它通过本地方法来调用操作系统API来获取系统相关数据。

Windows操作系统下Sigar.jar 依赖sigar-amd64-winnt.dll或sigar-x86-winnt.dll,linux 操作系统下则依赖libsigar-amd64-linux.so或libsigar-x86-linux.so。

Sigar可以跨平台,利用jni技术,核心由C语言实现的,非常好用,是一个开源的工具,提供了跨平台的系统信息收集的API。

  1. CPU信息: 包括基本信息(vendor、model、mhz、cacheSize)和统计信息(user、sys、idle、nice、wait)
  2. 文件系统信息: 包括Filesystem、Size、Used、Avail、Use%、Type
  3. 事件信息: 类似Service Control Manager
  4. 内存信息: 物理内存和交换内存的总数、使用数、剩余数;RAM的大小
  5. 网络信息: 包括 网络接口信息 和 网络路由 链接表信息 信息
  6. 进程信息: 包括每个进程的内存、CPU占用数、状态、参数、句柄
  7. IO信息: 包括IO的状态,读写大小等
  8. 服务状态信息
  9. 系统信息: 包括操作系统版本,系统资源限制情况,系统运行时间以及负载,JAVA的版本信息等.

建议:利用单例模式,保证只有一个Sigar对象,可有提高性能。

package com.jiepu.test;
 
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获取
            System.setProperty("java.library.path", "so");
            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<String, String> 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());
 
            switch (fs.getType()) {
                case 0: // TYPE_UNKNOWN :未知
                    break;
                case 1: // TYPE_NONE
                    break;
                case 2: // TYPE_LOCAL_DISK : 本地硬盘
                    FileSystemUsage usage = sigar.getFileSystemUsage(fs.getDirName());
                    // 文件系统总大小
                    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 + "%");
 
                    System.out.println(fs.getDevName() + "读出:    " + usage.getDiskReads());
                    System.out.println(fs.getDevName() + "写入:    " + usage.getDiskWrites());
                    break;
                case 3:// TYPE_NETWORK :网络
                    break;
                case 4:// TYPE_RAM_DISK :闪存
                    break;
                case 5:// TYPE_CDROM :光驱
                    break;
                case 6:// TYPE_SWAP :页面交换
                    break;
            }
 
        }
        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());//
        }
    }
}

2 jmx

通过jmx(Java自带)可以监控vm内存使用,系统内存使用等.

可能会碰到的问题:无法引入com.sun.management.OperatingSystemMXBean  
解决方案:Eclipse默认把这些受访问限制的API设成了ERROR。只要把Windows-Preferences-Java-Complicer-Errors/Warnings里面的
Deprecated and restricted API中的Forbidden references(access rules) 选为Warning就可以编译通过。

 从JDK1.5之后,Java开始提供包:java.lang.management 提供了一系列的用来在运行时管理和监督JVM和OS的管理接口。

Java自带的包可能目前还不是特别好用,但是随着发展,肯定会越来越方便。比如Java 9的 Process API 增强,可以方便的管理系统进程。

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;   
     
    /** cpu使用率. */   
    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;   
    }   
}   
  
    之后,建立bean的接口   
  
public interface IMonitorService {   
    public MonitorInfoBean getMonitorInfoBean() throws Exception;   
  
}   
  
  然后,就是最关键的,得到cpu的利用率,已用内存,可用内存,最大内存等信息。   
  
import java.io.InputStreamReader;   
import java.io.LineNumberReader;   
  
import sun.management.ManagementFactory;   
  
import com.sun.management.OperatingSystemMXBean;   
import java.io.*;   
import java.util.StringTokenizer;   
  
/**  
* 获取系统信息的业务逻辑实现类.  
* @author GuoHuang  
*/   
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;   
  
    /**  
     * 获得当前的监控对象.  
     * @return 返回构造好的监控对象  
     * @throws Exception  
     * @author GuoHuang  
     */   
    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());   
        }   
    }   
  
  
    /**  
     * 获得CPU使用率.  
     * @return 返回cpu使用率  
     * @author GuoHuang  
     */   
    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;   
        }   
    }   
  
    /**      
* 读取CPU信息.  
     * @param proc  
     * @return  
     * @author GuoHuang  
     */   
    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;   
                }   
                // 字段出现顺序:Caption,CommandLine,KernelModeTime,ReadOperationCount,   
                // ThreadCount,UserModeTime,WriteOperation   
                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;   
    }   
     
    /**     测试方法.  
     * @param args  
     * @throws Exception  
     * @author GuoHuang  
       */   
    public static void main(String[] args) throws Exception {   
        IMonitorService service = new MonitorServiceImpl();   
        MonitorInfoBean monitorInfo = service.getMonitorInfoBean();   
        System.out.println("cpu占有率=" + monitorInfo.getCpuRatio());   
         
        System.out.println("可使用内存=" + monitorInfo.getTotalMemory());   
        System.out.println("剩余内存=" + monitorInfo.getFreeMemory());   
        System.out.println("最大可使用内存=" + monitorInfo.getMaxMemory());   
         
        System.out.println("操作系统=" + monitorInfo.getOsName());   
        System.out.println("总的物理内存=" + monitorInfo.getTotalMemorySize() + "kb");   
        System.out.println("剩余的物理内存=" + monitorInfo.getFreeMemory() + "kb");   
        System.out.println("已使用的物理内存=" + monitorInfo.getUsedMemory() + "kb");   
        System.out.println("线程总数=" + monitorInfo.getTotalThread() + "kb");   
    }   
}   
  
    其中,Bytes类用来处理字符串   
  
   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;   
        }   
        return tgt;   
    }   
}   

3 系统命令

利用Java,在终端执行系统的命令。比如微软的TASKLIST.EXE可以输出当前运行进程列表信息。 可以用java执行TASKLIST.EXE然后获得输出。

Process p = Runtime.getRuntime().exec("ping " + ip);  
InputStreamReader ir = new InputStreamReader(p.getInputStream(),"gbk"); 

4 Windows 电量获取

通常的需求是在移动设备上获取电量。但是PC机的电量也是主机数据之一,并且很少有能实现此功能的包。

参考:http://www.coderlord.com/java/6/9/8/E8B7503436698.html

正在谈论笔记本电脑。标准Java SE API中不存在此类API。此信息仅在操作系统平台本机API中提供。您至少需要JNI或JNA(JavaWorld文章)才能进行通信使用平台本机API。

在Windows中,你想要挂钩SYSTEM_POWER_STATUS结构。它提供了你可能感兴趣的BatteryLifePercent属性。我在旧的forums.sun中找到了一个有用的基于JNA的代码片段。 

package com.example;

import java.util.ArrayList;
import java.util.List;

import com.sun.jna.Native;
import com.sun.jna.Structure;
import com.sun.jna.win32.StdCallLibrary;

public interface Kernel32 extends StdCallLibrary {

    public Kernel32 INSTANCE = (Kernel32) Native.loadLibrary("Kernel32", Kernel32.class);

    /**
     * @see http://msdn2.microsoft.com/en-us/library/aa373232.aspx
     */
    public class SYSTEM_POWER_STATUS extends Structure {
        public byte ACLineStatus;
        public byte BatteryFlag;
        public byte BatteryLifePercent;
        public byte Reserved1;
        public int BatteryLifeTime;
        public int BatteryFullLifeTime;

        @Override
        protected List<String> getFieldOrder() {
            ArrayList<String> fields = new ArrayList<String>();
            fields.add("ACLineStatus");
            fields.add("BatteryFlag");
            fields.add("BatteryLifePercent");
            fields.add("Reserved1");
            fields.add("BatteryLifeTime");
            fields.add("BatteryFullLifeTime");
            return fields;
        }

        /**
         * The AC power status
         */
        public String getACLineStatusString() {
            switch (ACLineStatus) {
                case (0): return "Offline";
                case (1): return "Online";
                default: return "Unknown";
            }
        }

        /**
         * The battery charge status
         */
        public String getBatteryFlagString() {
            switch (BatteryFlag) {
                case (1): return "High, more than 66 percent";
                case (2): return "Low, less than 33 percent";
                case (4): return "Critical, less than five percent";
                case (8): return "Charging";
                case ((byte) 128): return "No system battery";
                default: return "Unknown";
            }
        }

        /**
         * The percentage of full battery charge remaining
         */
        public String getBatteryLifePercent() {
            return (BatteryLifePercent == (byte) 255) ? "Unknown" : BatteryLifePercent + "%";
        }

        /**
         * The number of seconds of battery life remaining
         */
        public String getBatteryLifeTime() {
            return (BatteryLifeTime == -1) ? "Unknown" : BatteryLifeTime + " seconds";
        }

        /**
         * The number of seconds of battery life when at full charge
         */
        public String getBatteryFullLifeTime() {
            return (BatteryFullLifeTime == -1) ? "Unknown" : BatteryFullLifeTime + " seconds";
        }

        @Override
        public String toString() {
            StringBuilder sb = new StringBuilder();
            sb.append("ACLineStatus: " + getACLineStatusString() + "\n");
            sb.append("Battery Flag: " + getBatteryFlagString() + "\n");
            sb.append("Battery Life: " + getBatteryLifePercent() + "\n");
            sb.append("Battery Left: " + getBatteryLifeTime() + "\n");
            sb.append("Battery Full: " + getBatteryFullLifeTime() + "\n");
            return sb.toString();
        }
    }

    /**
     * Fill the structure.
     */
    public int GetSystemPowerStatus(SYSTEM_POWER_STATUS result);
}

main()方法:

Kernel32.SYSTEM_POWER_STATUS batteryStatus = new Kernel32.SYSTEM_POWER_STATUS();
Kernel32.INSTANCE.GetSystemPowerStatus(batteryStatus);

System.out.println(batteryStatus); // Shows result of toString() method.

这将在我的Latitude E5500上成功打印以下内容:

ACLineStatus: Online
Battery Flag: High, more than 66 percent
Battery Life: 100%
Battery Left: Unknown
Battery Full: Unknown

插上AC 10分钟后:

ACLineStatus: Offline
Battery Flag: High, more than 66 percent
Battery Life: 82%
Battery Left: 2954 seconds
Battery Full: Unknown