第一篇:JAVA获得设备信息
来源:互联网 发布:facebook 聊天软件 编辑:程序博客网 时间:2024/06/02 19:03
做Java开发时,可能会获得设备的一些信息,比如CPU、内存,做一些监控等,今天介绍一种JAVA获得设备信息的方式,使用的第三方包为sigar.jar(根据操作系统类型,还要添加对应的动态链接库)。
代码如下:
import java.net.InetAddress;import java.util.Set;import java.util.TreeSet;import org.hyperic.sigar.CpuInfo;import org.hyperic.sigar.FileSystem;import org.hyperic.sigar.FileSystemUsage;import org.hyperic.sigar.Mem;import org.hyperic.sigar.OperatingSystem;import org.hyperic.sigar.Sigar;import org.hyperic.sigar.SigarException;import org.hyperic.sigar.Swap;/** * 设备信息工具类 * * @author gjjiang * */public class DeviceUtils{ /** sigar对象,用于获得设备信息 **/ private Sigar sigar = null; /** * 初始化方法 */ public DeviceUtils() { sigar = new Sigar(); } /** * 关闭,释放sigar相关资源 */ public void close() { sigar.close(); } /** * 获得CPU信息 * * @return * @throws SigarException */ public CpuInfo[] getCpuInfo() throws SigarException { return sigar.getCpuInfoList(); } /** * 获得内存信息 * * @return * @throws SigarException */ public Mem getMem() throws SigarException { return sigar.getMem(); } /** * 获得系统页面文件交换区信息 * * @return * @throws SigarException */ public Swap getSwap() throws SigarException { return sigar.getSwap(); } /** * 取到当前操作系统的名称 * * @return */ public String getHostName() { String hostname = ""; try { hostname = InetAddress.getLocalHost().getHostName(); } catch (Exception exc) { try { hostname = sigar.getNetInfo().getHostName(); } catch (SigarException e) { hostname = "unknown"; } } return hostname; } /** * 获得操作系统信息 * * @return */ public OperatingSystem getOSInfo() { return OperatingSystem.getInstance(); } /** * 获取文件系统信息 * * @throws SigarException */ public FileSystem[] getFileSystemInfo() throws SigarException { return sigar.getFileSystemList(); } public FileSystemUsage getFileSystemUsage(String dirName) throws SigarException { return sigar.getFileSystemUsage(dirName); } /** * 获得网卡Mac地址 * * @return * @throws SigarException */ public Set<String> getMacs() throws SigarException { TreeSet<String> treeSet = new TreeSet<String>(); String[] list = sigar.getNetInterfaceList(); for (String string : list) { String mac = sigar.getNetInterfaceConfig(string).getHwaddr(); if (mac != null) { treeSet.add(mac); } } return treeSet; }}