获取系统相关信息 (CPU使用率 内存使用率 系统磁盘大小)
引言
在软件开个过程中,对于软件的稳定性和使用率也是我们需要关注的 。
使用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使用率 内存使用率 系统磁盘大小)的更多相关文章
- C#获取CPU和内存使用率
获取内存使用率 方式1: using System; using System.Runtime.InteropServices; namespace ConsoleApp1 { public clas ...
- Linux下使用java获取cpu、内存使用率
原文地址:http://www.voidcn.com/article/p-yehrvmep-uo.html 思路如下:Linux系统中可以用top命令查看进程使用CPU和内存情况,通过Runtime类 ...
- C#获取特定进程CPU和内存使用率
首先是获取特定进程对象,可以使用Process.GetProcesses()方法来获取系统中运行的所有进程,或者使用Process.GetCurrentProcess()方法来获取当前程序所对应的进程 ...
- Python获取CPU、内存使用率以及网络使用状态代码
Python获取CPU.内存使用率以及网络使用状态代码_python_脚本之家 http://www.jb51.net/article/134714.htm
- Ubuntu 16.04 标题栏实时显示上下行网速、CPU及内存使用率--indicator-sysmonitor
---------------------------------------------------------------------------- 原文地址:http://blog.csdn.N ...
- DSAPI 获取实时统计信息CPU/内存/硬盘/网络
有时,我们需要获取当前计算机中CPU.内存.硬盘.网络等实时信息,如下图:\ 要实现上述几项信息的获取,通常需要使用Timer控件来间隔获取,以便刷新最新的数据. 本示例中,放一个Timer控件,放一 ...
- Ubuntu 16.04 标题栏实时显示上下行网速、CPU及内存使用率
有时感觉网络失去响应,就通过Ubuntu 14.04自带的系统监视器程序来查看当前网速,但是这样很不方便,遂打算让网速显示在标题栏,那样就随时可直观的看到.一番搜索尝试后,成功实现!同时也实现了CPU ...
- 转:ZABBIX监控H3C设备的CPU和内存使用率
由于最近监控的H3C路由器经常出现死机现象,SNMP获取不到数据,后面检查发现是CPU使用率过高,直接导致无法处理SNMP请求,所以需求来了,怎样通过SNMP监控H3C路由器的CPU和内存使用率? ...
- Linux sysinfo获取系统相关信息
Linux中,可以用sysinfo来获取系统相关信息. #include <stdio.h> #include <stdlib.h> #include <errno.h& ...
随机推荐
- Excel上下标如何设置?
Excel表格怎么设置上下标?Excel上下标设置技巧 在21世纪的我们,平时的工作和学习中,经常会使用到一些专业的文档,比如方程式.数据的公式和科学计数等,其中均会涉及到许多的上下标符号输入以及使用 ...
- 池化技术(一)Druid是如何管理数据库连接的?
基于依赖程序的版本信息:druid:1.1.16 驱动程序mysql-connector-java:8.0.17 下一篇:HikariCP是如何管理数据库连接的 零.类图& ...
- fiddler 进行Android/IOS代理配置抓包
1.准备:Android+IOS设备 下载:fiddler抓包工具,不是最新版的链接: 链接:https://pan.baidu.com/s/1BaBfu2H4xgpsh1wmkfC8aQ ...
- mysql DDL 锁表
mysql DDL 锁表 select trx_state, trx_started, trx_mysql_thread_id, trx_query from information_schema.i ...
- 关于String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
关于 String path = request.getContextPath(); String basePath = request.getScheme()+"://"+req ...
- 基于V7的emWin多屏显示方案模板,同时驱动LCD和OLED例程
说明: 1.多屏驱动跟多图层驱动是类似的,可以使用函数GUI_SelectLayer做切换选择. 2.为了避免OLED闪烁问题,创建一个128*64bit的显存空间,然后使用emWin的GUI_TIM ...
- apt-get原理
apt-get 而这个步骤全要用户亲力亲为可能又有些麻烦,懒是科技发展的重要推动力.所以软件厂商自己编译好了很多二进制文件,只要系统和环境对应,下载之后就能直接安装. 但是如果下载了很多软件我想要管理 ...
- ZooKeeper(三):请求处理链路的创建过程解析
我们知道,zk就是一个个处理链组成的. 但是,这些处理链是在什么创建的呢? ZooKeeper 中有三种角色的服务节点存在: Leader, Follower, Observer . 而每个服务节点的 ...
- 常用类-excel转csv
public class ExcelFileHelper { public static bool SaveAsCsv(string excelFilePath, string destination ...
- centos添加用户并赋予管理员权限
用centos时,root用户一般都是超级管理员使用的,一般不轻易给别人,但是有时候同事安装软件时需要root账号,又不得不给,只能重新建一个用户,并赋予管理员权限.下面介绍创建用户并赋予管理员权限的 ...