通过Java代码获取系统信息

  在开发中,我们需要获取JVM中的信息,以及操作系统信息,内存信息,CPU信息,磁盘信息,网络信息等,通过Java的API不能获取内存等信息,需要sigar的第三方依赖包。

①:加入依赖

  

<dependency>
	<groupId>org.hyperic.sigar</groupId>
	<artifactId>com.springsource.org.hyperic.sigar</artifactId>
	<version>1.6.3</version>
</dependency>
<dependency>
	<groupId>org.kaazing</groupId>
	<artifactId>sigar.dist</artifactId>
	<version>1.0.0.0</version>
	<classifier>distribution</classifier>
	<type>zip</type>
</dependency>

②:将POM下载的sigar.dist压缩包中的sigar 系统文件放到 C:\Program Files\Java\jdk1.8.0_20\bin中 即{JAVA_HOME}/bin下

③ 相应的工具方法

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())
					|| NetFlags.NULL_HWADDR.equals(cfg.getHwaddr())) {
				continue;
			}
			System.out.println(cfg.getName() + "IP地址:" + cfg.getAddress());
			System.out.println(cfg.getName() + "网关广播地址:" + cfg.getBroadcast());
			System.out.println(cfg.getName() + "网卡MAC地址:" + cfg.getHwaddr());
			System.out.println(cfg.getName() + "子网掩码:" + cfg.getNetmask());
			System.out.println(cfg.getName() + "网卡描述信息:" + cfg.getDescription());
			System.out.println(cfg.getName() + "网卡类型:" + cfg.getType());
		}
	}

	private static void net() throws SigarException {
		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());
			System.out.println("子网掩码:" + ifConfig.getNetmask());
			if((ifConfig.getFlags() & 1L) <= 0) {
				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 file() throws SigarException {
		Sigar sigar = new Sigar();
		FileSystem[] fsList = sigar.getFileSystemList();
		try {
			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());
				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_UNKNOEN 未知
					break;
				case 1: //TYPE_NONE
					break;
				case 2: //TYPE_LOCAL_DISK 本地硬盘
				    //文件系统总大小
					System.out.println(fs.getDevName() +"总大小:" + usage.getTotal() +"");
					//文件系统剩余大小
					System.out.println(fs.getDevName() +"剩余大小:" + usage.getFree() +"");
					//文件系统可用大小
					System.out.println(fs.getDevName() +"可用大小:" + usage.getAvail() +"");
					//文件系统已经使用量
					System.out.println(fs.getDevName() +"已经使用量:" + usage.getUsed() +"");
					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());
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
	}

	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 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 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());
			System.out.println("CPU生产商:" + info.getVendor());
			System.out.println("CPU类别:" + info.getModel());
			System.out.println("CPU缓存数量:" + info.getCacheSize());
			printCpuPerc(cpuList[i]);
		}
	}

	private static void printCpuPerc(CpuPerc cpuPerc) {
		System.out.println("CPU用户使用率:" + CpuPerc.format(cpuPerc.getUser()) );
		System.out.println("CPU系统使用率:" + CpuPerc.format(cpuPerc.getSys()) );
		System.out.println("CPU当前等待率:" + CpuPerc.format(cpuPerc.getWait()) );
		System.out.println("CPU当前错误率:" + CpuPerc.format(cpuPerc.getNice()) );
		System.out.println("CPU当前空闲率:" + CpuPerc.format(cpuPerc.getIdle()) );
		System.out.println("CPU总的使用率:" + CpuPerc.format(cpuPerc.getCombined()) );
	}

	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.vendor"));
		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"));
	}

  ④:测试方法

    

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 e) {
            e.printStackTrace();
        }
    }

原文地址:https://www.cnblogs.com/kangzhipeng/p/11029573.html

时间: 2024-11-08 02:50:14

通过Java代码获取系统信息的相关文章

如何使用Java代码获取文件、文件流或字符串的编码方式

今天通过网络资源研究了一下如何使用Java代码获取文件.文件流或字符串的编码方式,现将代码与大家分享: package com.ghj.packageoftool; import info.monitorenter.cpdetector.io.ASCIIDetector; import info.monitorenter.cpdetector.io.ByteOrderMarkDetector; import info.monitorenter.cpdetector.io.CodepageDete

如何使用Java代码获取Android移动终端Mac地址

快下班了,现在总结一下如何使用Java代码获取Android移动终端Mac地址: 通过设备开通WiFi连接获取Mac地址是最可取的,代码如下: /** * 设备开通WiFi连接,通过wifiManager获取Mac地址 * * @author 高焕杰 */ public static String getMacFromWifi(Context context){ ConnectivityManager connectivityManager = (ConnectivityManager) con

Java代码获取NTP服务器时间

apache的commons-net包下面有ntp相关的实现类,主要类有: 1  org.apache.commons.net.ntp.NTPUDPClient ? 1  org.apache.commons.net.ntp.TimeInfo 类NTPUDPClient中相关方法: ? 1  TimeInfo getTime(InetAddress host, int port) throws IOException ? 1 TimeInfo getTime(InetAddress host) 

java代码获取pdf文件第一页作为封面缩略图

package gcjsxh.util; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileOutputStream; import java.util.Iterator; import javax.imageio.IIOImage; import javax.imageio.ImageIO; import javax.imageio.ImageWriter; import javax.ima

Java代码获取所有系统属性

Properties props = System.getProperties();           Iterator<Entry<Object, Object>> it = props.entrySet().iterator();         while(it.hasNext()) {             Entry<Object, Object> ent = it.next();             System.out.println(ent.ge

java代码获取jdbc链接properties

public static String getDirPath() { Resource resource = null; Properties props = null; String driverClass = null; try { resource = new ClassPathResource("/data.properties"); props = PropertiesLoaderUtils.loadProperties(resource); driverClass= (S

java代码获取ip地址

public class IpTool { public static void main(String[] args) { IpTool ipTool=new IpTool(); System.out.println(ipTool.getLocalIP()); } /** * * 判斷當前操作是否Windows. * * @return true---是Windows操作系統 */ private boolean isWindowsOS() { boolean isWindowsOS = fa

java代码获取当前时间是本周、本月、本年的第几天

public static void getWeekMonthYear(){ Map<String, Integer> mapInt = new LinkedHashMap<String, Integer>(); Calendar calendar = Calendar.getInstance(); Date today = new Date(); calendar.setTime(today);// 此处可换为具体某一时间 int weekDay = calendar.get(C

Java如何获取系统cpu、内存、硬盘信息

1 概述 前段时间摸索在Java中怎么获取系统信息包括cpu.内存.硬盘信息等,刚开始使用Java自带的包进行获取,但这样获取的内存信息不够准确并且容易出现找不到相应包等错误,所以后面使用sigar插件进行获取.下面列举出了这两种方式获取系统信息的方式及代码. 2 使用Java自带包获取系统信息 2.1 使用Java自带包获取系统信息代码如下: 2.1.1 Bytes.java public class Bytes { public static String substring(String