java程序实现获取计算机cpu利用率和内存使用信息的代码.docx
《java程序实现获取计算机cpu利用率和内存使用信息的代码.docx》由会员分享,可在线阅读,更多相关《java程序实现获取计算机cpu利用率和内存使用信息的代码.docx(14页珍藏版)》请在冰豆网上搜索。
java程序实现获取计算机cpu利用率和内存使用信息的代码
利用java程序实现获取计算机cpu利用率和内存使用信息。
创建一个Bean用来存贮要得到的信
publicclassMonitorInfoBean{
/**可使用内存.*/
privatelongtotalMemory;
/**剩余内存.*/
privatelongfreeMemory;
/**最大可使用内存.*/
privatelongmaxMemory;
/**操作系统.*/
privateStringosName;
/**总的物理内存.*/
privatelongtotalMemorySize;
/**剩余的物理内存.*/
privatelongfreePhysicalMemorySize;
/**已使用的物理内存.*/
privatelongusedMemory;
/**线程总数.*/
privateinttotalThread;
/**cpu使用率.*/
privatedoublecpuRatio;
publiclonggetFreeMemory({
returnfreeMemory;
}
publicvoidsetFreeMemory(longfreeMemory{
this.freeMemory=freeMemory;
}
publiclonggetFreePhysicalMemorySize({
returnfreePhysicalMemorySize;
}
publicvoidsetFreePhysicalMemorySize(longfreePhysicalMemorySize{this.freePhysicalMemorySize=freePhysicalMemorySize;
}
publiclonggetMaxMemory({
returnmaxMemory;
}
publicvoidsetMaxMemory(longmaxMemory{
this.maxMemory=maxMemory;
}
publicStringgetOsName({
returnosName;
}
publicvoidsetOsName(StringosName{
this.osName=osName;
}
publiclonggetTotalMemory({
returntotalMemory;
}
publicvoidsetTotalMemory(longtotalMemory{
this.totalMemory=totalMemory;
}
publiclonggetTotalMemorySize({
returntotalMemorySize;
}
publicvoidsetTotalMemorySize(longtotalMemorySize{
this.totalMemorySize=totalMemorySize;
}
publicintgetTotalThread({
returntotalThread;
}
publicvoidsetTotalThread(inttotalThread{
this.totalThread=totalThread;
}
publiclonggetUsedMemory({
returnusedMemory;
publicvoidsetUsedMemory(longusedMemory{
this.usedMemory=usedMemory;
}
publicdoublegetCpuRatio({
returncpuRatio;
}
publicvoidsetCpuRatio(doublecpuRatio{
this.cpuRatio=cpuRatio;
}
}
之后,建立bean的接口
publicinterfaceIMonitorService{
publicMonitorInfoBeangetMonitorInfoBean(throwsException;
}
然后,就是最关键的,得到cpu的利用率,已用内存,可用内存,最大内存等信息。
importjava.io.InputStreamReader;
importjava.io.LineNumberReader;
importsun.management.ManagementFactory;
importcom.sun.management.OperatingSystemMXBean;
importjava.io.*;
importjava.util.StringTokenizer;
/**
*获取系统信息的业务逻辑实现类.
*@authorGuoHuang
*/
publicclassMonitorServiceImplimplementsIMonitorService{
privatestaticfinalintCPUTIME=30;
privatestaticfinalintPERCENT=100;
privatestaticfinalintFAULTLENGTH=10;
privatestaticfinalFileversionFile=newFile("/proc/version";
privatestaticStringlinuxVersion=null;
/**
*获得当前的监控对象.
*@return返回构造好的监控对象
*@throwsException
*@authorGuoHuang
*/
publicMonitorInfoBeangetMonitorInfoBean(throwsException{
intkb=1024;
//可使用内存
longtotalMemory=Runtime.getRuntime(.totalMemory(/kb;
//剩余内存
longfreeMemory=Runtime.getRuntime(.freeMemory(/kb;
//最大可使用内存
longmaxMemory=Runtime.getRuntime(.maxMemory(/kb;
OperatingSystemMXBeanosmxb=(OperatingSystemMXBeanManagementFactory
.getOperatingSystemMXBean(;
//操作系统
StringosName=System.getProperty("os.name";
//总的物理内存
longtotalMemorySize=osmxb.getTotalPhysicalMemorySize(/kb;
//剩余的物理内存
longfreePhysicalMemorySize=osmxb.getFreePhysicalMemorySize(/kb;//已使用的物理内存
longusedMemory=(osmxb.getTotalPhysicalMemorySize(-osmxb
.getFreePhysicalMemorySize(
/kb;
//获得线程总数
ThreadGroupparentThread;
for(parentThread=Thread.currentThread(.getThreadGroup(;parentThread.getParent(!
=null;parentThread=parentThread.getParent(
;
inttotalThread=parentThread.activeCount(;
doublecpuRatio=0;
if(osName.toLowerCase(.startsWith("windows"{
cpuRatio=this.getCpuRatioForWindows(;
}
else{
cpuRatio=this.getCpuRateForLinux(;
}
//构造返回对象
MonitorInfoBeaninfoBean=newMonitorInfoBean(;
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;
returninfoBean;
}
privatestaticdoublegetCpuRateForLinux({
InputStreamis=null;
InputStreamReaderisr=null;
BufferedReaderbrStat=null;
StringTokenizertokenStat=null;
try{
System.out.println("GetusagerateofCUP,linuxversion:
"+linuxVersion;
Processprocess=Runtime.getRuntime(.exec("top-b-n1";
is=process.getInputStream(;
isr=newInputStreamReader(is;
brStat=newBufferedReader(isr;
if(linuxVersion.equals("2.4"{
brStat.readLine(;
brStat.readLine(;
brStat.readLine(;
brStat.readLine(;
tokenStat=newStringTokenizer(brStat.readLine(;
tokenStat.nextToken(;
tokenStat.nextToken(;
Stringuser=tokenStat.nextToken(;
tokenStat.nextToken(;
Stringsystem=tokenStat.nextToken(;
tokenStat.nextToken(;
Stringnice=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("%";
floatuserUsage=newFloat(user.floatValue(;
floatsystemUsage=newFloat(system.floatValue(;
floatniceUsage=newFloat(nice.floatValue(;
return(userUsage+systemUsage+niceUsage/100;
}else{
brStat.readLine(;
brStat.readLine(;
tokenStat=newStringTokenizer(brStat.readLine(;
tokenStat.nextToken(;
tokenStat.nextToken(;
tokenStat.nextToken(;
tokenStat.nextToken(;
tokenStat.nextToken(;
tokenStat.nextToken(;
tokenStat.nextToken(;
StringcpuUsage=tokenStat.nextToken(;
System.out.println("CPUidle:
"+cpuUsage;
Floatusage=newFloat(cpuUsage.substring(0,cpuUsage.indexOf("%";
return(1-usage.floatValue(/100;
}
}catch(IOExceptionioe{
System.out.println(ioe.getMessage(;
freeResource(is,isr,brStat;
return1;
}finally{
freeResource(is,isr,brStat;
}
}
privatestaticvoidfreeResource(InputStreamis,InputStreamReaderisr,BufferedReaderbr{
try{
if(is!
=null
is.close(;
if(isr!
=null
isr.close(;
if(br!
=null
br.close(;
}catch(IOExceptionioe{
System.out.println(ioe.getMessage(;
}
}
/**
*获得CPU使用率.
*@return返回cpu使用率
*@authorGuoHuang
*/
privatedoublegetCpuRatioForWindows({
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];
returnDouble.valueOf(
PERCENT*(busytime/(busytime+idletime
.doubleValue(;
}else{
return0.0;
}
}catch(Exceptionex{
ex.printStackTrace(;
return0.0;
}
}
/**
*读取CPU信息.
*@paramproc
*@return
*@authorGuoHuang
*/
privatelong[]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(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(continue;
}
//字段出现顺序:
Caption,CommandLine,KernelModeTime,ReadOperationCount,
//ThreadCount,UserModeTime,WriteOperation
Stringcaption=Bytes.substring(line,capidx,cmdidx-1
.trim(;
Stringcmd=Bytes.substring(line,cmdidx,kmtidx-1.trim(;
if(cmd.indexOf("wmic.exe">=0{
continue;
}
//log.info("line="+line;
if(caption.equals("SystemIdleProcess"
||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;
returnretn;
}catch(Exceptionex{
ex.printStackTrace(;
}finally{
try{
proc.getInputStream(.close(;
}catch(Exceptione{
e.printStackTrace(;
}
}
returnnull;
}
/**测试方法.
*@paramargs
*@throwsException
*@authorGuoHuang
*/
publicstaticvoidmain(String[]argsthrowsException{
IMonitorServiceservice=newMonitorServiceImpl(;
MonitorInfoBeanmonitorInfo=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类用来处理字符串
publicclassBytes{
publicstaticStringsubstring(Stringsrc,intstart_idx,intend_idx{byte[]b=src.getBytes(;
Stringtgt="";
for(inti=start_idx;i<=end_idx;i++{
tgt+=(charb[i];
}
returntgt;
}
}