获取系统相关信息 (CPU使用率 内存使用率 系统磁盘大小)

时间:2024-04-19 20:08:32

引言

在软件开个过程中,对于软件的稳定性和使用率也是我们需要关注的 。

 使用sigar来监控,简单方便!

 使用说明:下载sigar jar及配合sigar的dll文件来用,需要将dll文件放到JDK下的bin文件夹下,供sigar程序调用。以下程序经过测试,完全可用!
 package com.thinkgem.jeesite.common.utils;

 import java.io.File;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.text.DecimalFormat; import javax.swing.filechooser.FileSystemView; import org.hyperic.sigar.Mem;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException; /**
*
*@description:功能说明:获取系统相关信息 (内存使用率 cpu使用率 磁盘大小及使用率)
*@author:zsq
*Creation date:2019年6月28日 下午3:24:39
*/
public class SystemRelatedInfoUtils
{
private static final int CPUTIME=500; private static final int PERCENT=100; private static final int FAULTLENGTH=10; /**
* 获得系统时间.
* @return 获得系统时间.
* @author zsq
* Creation date: 2019年6月28日 下午3:30:39
*/
public static String getSystemDate(){
String date=DateUtils.getDate();
return "报告日期:"+date;
} /**
* 获得CPU使用率.
* @return 返回cpu使用率
* @author amg
* Creation date: 2019年6月28日 下午3:35:39
*/
public static String 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 "CPU使用率:"
+ Double.valueOf(
PERCENT * (busytime) * 1.0
/ (busytime + idletime)).intValue()
+ "%";
} else {
return "CPU使用率:" + 0 + "%";
}
} catch (Exception ex) {
ex.printStackTrace();
return "CPU使用率:" + 0 + "%";
}
} /**
* 读取CPU信息.
* @param proc
* @return
* @author amg
* Creation date: 2019年6月28日 下午3:40:39
*/
private static 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 = substring(line, capidx, cmdidx - 1).trim();
String cmd = substring(line, cmdidx, kmtidx - 1).trim();
if (cmd.indexOf("wmic.exe") >= 0) {
continue;
}
String s1 = substring(line, kmtidx, rocidx - 1).trim();
String s2 = substring(line, umtidx, wocidx - 1).trim();
if (caption.equals("System Idle Process")
|| 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;
return retn;
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
proc.getInputStream().close();
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
} /**
* 由于String.subString对汉字处理存在问题(把一个汉字视为一个字节),因此在
* 包含汉字的字符串时存在隐患,现调整如下:
* @param src 要截取的字符串
* @param start_idx 开始坐标(包括该坐标)
* @param end_idx 截止坐标(包括该坐标)
* @return
*/
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[i];
}
return tgt;
} /**
* 获取内存使用率.
* @return 获得内存使用率.
* @author amg
* Creation date: 2019年6月28日 下午4:30:39
*/
@SuppressWarnings("unused")
public static String getMemory() {
Sigar sigar=new Sigar();
Mem men;
String string="";
try
{
men = sigar.getMem();
double total=men.getTotal()/1024;
double use=men.getUsed()/1024;
//double free=men.getFree()/1024;
double rs=(use/total)*100;
//内存总量
// System.out.println("内存总量: "+total+" k av");
//当前内存使用量  
// System.out.println("当前内存使用量:  "+use+" k use");
// 当前内存剩余量  
// System.err.println("当前内存剩余量: "+free+" k free");
// System.err.println("*****内存使用率: "+String.format("%.2f", rs)+"%");
string="内存使用率: "+String.format("%.2f", rs)+"%";
} catch (SigarException e)
{
e.printStackTrace();
}
return string;
} /**
* 获取磁盘信息.
* @return 获取磁盘信息.
* @author amg
* Creation date: 2019年6月28日 下午4:40:39
*/
public static String getDisk(){
// 当前文件系统类
FileSystemView fsv = FileSystemView.getFileSystemView();
// 列出所有windows 磁盘
File[] fs = File.listRoots();
double totalSpace=0f;
double freeSpace=0f;
// 显示磁盘卷标
for (int i = 0; i < fs.length; i++) {
//System.out.println(fsv.getSystemDisplayName(fs[i]));
// System.out.print("总大小" + FormetFileSize(fs[i].getTotalSpace()));
// System.out.println("剩余" + FormetFileSize(fs[i].getFreeSpace()));
totalSpace+=Double.valueOf(FormetFileSize(fs[i].getTotalSpace()));
freeSpace+=Double.valueOf(FormetFileSize(fs[i].getFreeSpace()));
} // System.err.println("*****磁盘总大小: "+String.format("%.0f",totalSpace)+"G");
// System.err.println("*****磁盘剩余: "+String.format("%.0f",freeSpace)+"G");
String totalSpaceStr="";
String freeSpaceStr="";
//空间大于1024G就用T
if(totalSpace>1024){
totalSpace= totalSpace/1024;
totalSpaceStr=String.format("%.2f",totalSpace)+"T";
}else{
totalSpaceStr=String.format("%.0f",totalSpace)+"G";
}
if(freeSpace>1024){
freeSpace= freeSpace/1024;
freeSpaceStr=String.format("%.2f",freeSpace)+"T";
}else{
freeSpaceStr=String.format("%.2f",freeSpace)+"G";
} double rs=((totalSpace-freeSpace)/totalSpace)*100;
String message="磁盘空间: 总大小"+totalSpaceStr+", 已用 "+String.format("%.2f",rs)+"%"+", 剩余:"+freeSpaceStr;
return message;
}
/*
* 格式化 计算出 M G T(磁盘大小)
*/
public static String FormetFileSize(long fileS) {
DecimalFormat df = new DecimalFormat("#.00");
String fileSizeString = "";
if (fileS < 1024) {
fileSizeString = df.format((double) fileS);//B
} else if (fileS < 1048576) {
fileSizeString = df.format((double) fileS / 1024) ;//K
} else if (fileS < 1073741824) {
fileSizeString = df.format((double) fileS / 1048576);//M
}else {
fileSizeString = df.format((double) fileS / 1073741824);//G
} return fileSizeString;
} public static void main(String[] args)
{
SystemRelatedInfoUtils srf=new SystemRelatedInfoUtils();
long start=System.currentTimeMillis();
System.out.println(getSystemDate());
System.out.println(getCpuRatioForWindows());
long end=System.currentTimeMillis();
//System.out.println("用时:"+(end-start)/1000+"s");
System.err.println(getMemory());
System.err.println(getDisk());
}
}

运行效果:

获取系统相关信息 (CPU使用率 内存使用率 系统磁盘大小)