使用Java获取系统信息的常用代码整理总结
1.获取CPU和内存信息
importjava.io.InputStreamReader; importjava.io.LineNumberReader; importjava.util.ArrayList; importjava.util.List; importmytools.com.sun.management.OperatingSystemMXBean; importmytools.java.io.File; importmytools.java.lang.management.ManagementFactory; /** *获取windows系统信息(CPU,内存,文件系统) *@authorlibing * */ publicclassWindowsInfoUtil{ privatestaticfinalintCPUTIME=500; privatestaticfinalintPERCENT=100; privatestaticfinalintFAULTLENGTH=10; publicstaticvoidmain(String[]args){ System.out.println(getCpuRatioForWindows()); System.out.println(getMemery()); System.out.println(getDisk()); } //获取内存使用率 publicstaticStringgetMemery(){ OperatingSystemMXBeanosmxb=(OperatingSystemMXBean)ManagementFactory.getOperatingSystemMXBean(); //总的物理内存+虚拟内存 longtotalvirtualMemory=osmxb.getTotalSwapSpaceSize(); //剩余的物理内存 longfreePhysicalMemorySize=osmxb.getFreePhysicalMemorySize(); Doublecompare=(Double)(1-freePhysicalMemorySize*1.0/totalvirtualMemory)*100; Stringstr="内存已使用:"+compare.intValue()+"%"; returnstr; } //获取文件系统使用率 publicstaticList<String>getDisk(){ //操作系统 List<String>list=newArrayList<String>(); for(charc='A';c<='Z';c++){ StringdirName=c+":/"; Filewin=newFile(dirName); if(win.exists()){ longtotal=(long)win.getTotalSpace(); longfree=(long)win.getFreeSpace(); Doublecompare=(Double)(1-free*1.0/total)*100; Stringstr=c+":盘已使用"+compare.intValue()+"%"; list.add(str); } } returnlist; } //获得cpu使用率 publicstaticStringgetCpuRatioForWindows(){ try{ StringprocCmd=System.getenv("windir")+"//system32//wbem//wmic.exeprocessgetCaption,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){ longidletime=c1[0]-c0[0]; longbusytime=c1[1]-c0[1]; return"CPU使用率:"+Double.valueOf(PERCENT*(busytime)*1.0/(busytime+idletime)).intValue()+"%"; }else{ return"CPU使用率:"+0+"%"; } }catch(Exceptionex){ ex.printStackTrace(); return"CPU使用率:"+0+"%"; } } //读取cpu相关信息 privatestaticlong[]readCpu(finalProcessproc){ long[]retn=newlong[2]; try{ proc.getOutputStream().close(); InputStreamReaderir=newInputStreamReader(proc.getInputStream()); LineNumberReaderinput=newLineNumberReader(ir); Stringline=input.readLine(); if(line==null||line.length()<FAULTLENGTH){ returnnull; } intcapidx=line.indexOf("Caption"); intcmdidx=line.indexOf("CommandLine"); introcidx=line.indexOf("ReadOperationCount"); intumtidx=line.indexOf("UserModeTime"); intkmtidx=line.indexOf("KernelModeTime"); intwocidx=line.indexOf("WriteOperationCount"); longidletime=0; longkneltime=0; longusertime=0; while((line=input.readLine())!=null){ if(line.length()<wocidx){ continue; } //字段出现顺序:Caption,CommandLine,KernelModeTime,ReadOperationCount, //ThreadCount,UserModeTime,WriteOperation Stringcaption=substring(line,capidx,cmdidx-1).trim(); Stringcmd=substring(line,cmdidx,kmtidx-1).trim(); if(cmd.indexOf("wmic.exe")>=0){ continue; } Strings1=substring(line,kmtidx,rocidx-1).trim(); Strings2=substring(line,umtidx,wocidx-1).trim(); if(caption.equals("SystemIdleProcess")||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; returnretn; }catch(Exceptionex){ ex.printStackTrace(); }finally{ try{ proc.getInputStream().close(); }catch(Exceptione){ e.printStackTrace(); } } returnnull; } /** *由于String.subString对汉字处理存在问题(把一个汉字视为一个字节),因此在包含汉字的字符串时存在隐患,现调整如下: *@paramsrc要截取的字符串 *@paramstart_idx开始坐标(包括该坐标) *@paramend_idx截止坐标(包括该坐标) *@return */ privatestaticStringsubstring(Stringsrc,intstart_idx,intend_idx){ byte[]b=src.getBytes(); Stringtgt=""; for(inti=start_idx;i<=end_idx;i++){ tgt+=(char)b[i]; } returntgt; } }
2.获取本机的IP地址:
privatestaticStringgetIpAddress()throwsUnknownHostException{ InetAddressaddress=InetAddress.getLocalHost(); returnaddress.getHostAddress(); }
3.获得网卡地址
publicstaticStringgetMACAddress(){ Stringaddress=""; Stringos=System.getProperty("os.name"); StringosUser=System.getProperty("user.name"); if(os!=null&&os.startsWith("Windows")){ try{ Stringcommand="cmd.exe/cipconfig/all"; Processp=Runtime.getRuntime().exec(command); BufferedReaderbr=newBufferedReader(newInputStreamReader(p.getInputStream())); Stringline; while((line=br.readLine())!=null){ if(line.indexOf("PhysicalAddress")>0){ intindex=line.indexOf(":"); index+=2; address=line.substring(index); break; } } br.close(); returnaddress.trim(); } catch(IOExceptione){ } } returnaddress; }
4.获得操作系统帐号
StringosUser=System.getProperty("user.name");
5.获得操作系统版本
importjava.util.Properties; Propertiesprops=System.getProperties();//获得系统属性集 StringosName=props.getProperty("os.name");//操作系统名称 StringosArch=props.getProperty("os.arch");//操作系统构架 StringosVersion=props.getProperty("os.version");//操作系统版本
6.一些常用的信息获得方式整理
java.version Java运行时环境版本
java.vendor Java运行时环境供应商
java.vendor.url Java供应商的URL
java.home Java安装目录
java.vm.specification.version Java虚拟机规范版本
java.vm.specification.vendor Java虚拟机规范供应商
java.vm.specification.name Java虚拟机规范名称
java.vm.version Java虚拟机实现版本
java.vm.vendor Java虚拟机实现供应商
java.vm.name Java虚拟机实现名称
java.specification.version Java运行时环境规范版本
java.specification.vendor Java运行时环境规范供应商
java.specification.name Java运行时环境规范名称
java.class.version Java类格式版本号
java.class.path Java类路径
java.library.path 加载库时搜索的路径列表
java.io.tmpdir 默认的临时文件路径
java.compiler 要使用的JIT编译器的名称
java.ext.dirs 一个或多个扩展目录的路径
os.name 操作系统的名称
os.arch 操作系统的架构
os.version 操作系统的版本
file.separator 文件分隔符(在UNIX系统中是“/”)
path.separator 路径分隔符(在UNIX系统中是“:”)
line.separator 行分隔符(在UNIX系统中是“/n”)
user.name 用户的账户名称
user.home 用户的主目录
user.dir 用户的当前工作目录