获取系统相关信息 (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& ...
随机推荐
- QT Creator: The process could not be started!
如果往工程里面增加了uac.manifest 文件后,QT creator不通过管理员启动的话,若要debug程序的话,就会提示 “The process could not be started!” ...
- 字节码联盟成立,WebAssembly 生态将完善网络安全性
近日 Mozilla.Fastly.Intel 与 Red Hat 宣布成立联合组织 Bytecode Alliance(字节码联盟),该联盟旨在通过协作实施标准和提出新标准,以完善 WebAssem ...
- 第二篇:C++画圆
安装GUI开发工具easyX #include <graphics.h>#include <Windows.h> int main(void) { initgraph(640, ...
- 20.never give up
- windows7使用vhd虚拟磁盘
操作系统 : windows7_x64 创建vhd 磁盘管理 --> 操作 --> 创建vhd 挂载vhd 脚本: rem 挂载VHD @echo off (echo select vdi ...
- Swoole 启动一个服务,开启了哪些进程和线程?
目录 概述 代码 小结 概述 Swoole 启动一个服务,开启了哪些进程和线程? 为了解决这个问题,咱们启动一个最简单的服务,一起看看究竟启动了哪些进程和线程? 然后结合官网运行流程图,对每个进程和线 ...
- GROUP BY中的WITH CUBE、WITH ROLLUP原理测试及GROUPING应用
前几天,看到一个群友用WITH ROLLUP运算符.由于自个儿没用过,看到概念及结果都云里雾里的,所以突然来了兴趣对生成结果测了一番. 一.概念: WITH CUBE:生成的结果集显示了所选列中值的所 ...
- .net core 反射的介绍与使用
1. 概述反射 通过反射可以提供类型信息,从而使得我们开发人员在运行时能够利用这些信息构造和使用对象. 反射机制允许程序在执行过程中动态地添加各种功能. 2. Type类的介绍 是BCL(基 ...
- 彻底理解volatile,领悟其中奥妙
本人免费整理了Java高级资料,涵盖了Java.Redis.MongoDB.MySQL.Zookeeper.Spring Cloud.Dubbo高并发分布式等教程,一共30G,需要自己领取.传送门:h ...
- JavaScript基础6
计时器 setInterval() 按照指定周期来调用函数或计算表达式 以毫秒计算 语法 setInterval(code,millisec[,“lang”]) code 要调用的函 ...