Java如何获取系统cpu、内存、硬盘信息

简介:
 1 概述
  前段时间摸索在 Java中怎么获取系统信息包括cpu、内存、硬盘信息等,刚开始使用Java自带的包进行获取,但这样获取的内存信息不够准确并且容易出现找不到相应包等错误,所以后面使用sigar插件进行获取。下面列举出了这两种方式获取系统信息的方式及代码。
   2 使用Java自带包获取系统信息
   2.1 使用Java自带包获取系统信息代码如下:
  2.1.1 Bytes.java
public class Bytes {
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;
}
}
  2.1.2 IMonitorService.java
  public interface IMonitorService {
  public MonitorInfoBean getMonitorInfoBean() throws Exception;
  }
  2.1.3 MonitorInfoBean.java
public class MonitorInfoBean {
private long totalMemory;
private long freeMemory;
private long maxMemory;
private String osName;
private long totalMemorySize;
private long freePhysicalMemorySize;
private long usedMemory;
private int totalThread;
private double cpuRatio;
public long getFreeMemory() {
return freeMemory;
}
public void setFreeMemory(long freeMemory) {
this.freeMemory = freeMemory;
}
public long getFreePhysicalMemorySize() {
return freePhysicalMemorySize;
}
public void setFreePhysicalMemorySize(long freePhysicalMemorySize) {
this.freePhysicalMemorySize = freePhysicalMemorySize;
}
public long getMaxMemory() {
return maxMemory;
}
public void setMaxMemory(long maxMemory) {
this.maxMemory = maxMemory;
}
public String getOsName() {
return osName;
}
public void setOsName(String osName) {
this.osName = osName;
}
public long getTotalMemory() {
return totalMemory;
}
public void setTotalMemory(long totalMemory) {
this.totalMemory = totalMemory;
}
public long getTotalMemorySize() {
return totalMemorySize;
}
public void setTotalMemorySize(long totalMemorySize) {
this.totalMemorySize = totalMemorySize;
}
public int getTotalThread() {
return totalThread;
}
public void setTotalThread(int totalThread) {
this.totalThread = totalThread;
}
public long getUsedMemory() {
return usedMemory;
}
public void setUsedMemory(long usedMemory) {
this.usedMemory = usedMemory;
}
public double getCpuRatio() {
return cpuRatio;
}
public void setCpuRatio(double cpuRatio) {
this.cpuRatio = cpuRatio;
}
}
 2.1.4
import java.io.InputStreamReader;
import java.io.LineNumberReader;
//import sun.management.ManagementFactory;
//import com.sun.management.OperatingSystemMXBean;
import java.io.*;
import java.lang.management.ManagementFactory;
import java.util.StringTokenizer;
public class MonitorServiceImpl implements IMonitorService {
private static final int CPUTIME = 30;
private static final int PERCENT = 100;
private static final int FAULTLENGTH = 10;
private static final File versionFile = new File("/proc/version");
private static String linuxVersion = null;
public MonitorInfoBean getMonitorInfoBean() throws Exception {
int kb = 1024;
long totalMemory = Runtime.getRuntime().totalMemory() / kb;
long freeMemory = Runtime.getRuntime().freeMemory() / kb;
long maxMemory = Runtime.getRuntime().maxMemory() / kb;
// OperatingSystemMXBean osmxb = (OperatingSystemMXBean)
// ManagementFactory
// .getOperatingSystemMXBean();
// String osName = System.getProperty("os.name");
// long totalMemorySize = osmxb.getTotalPhysicalMemorySize() / kb;
// long freePhysicalMemorySize = osmxb.getFreePhysicalMemorySize() / kb;
// long usedMemory = (osmxb.getTotalPhysicalMemorySize() - osmxb
// .getFreePhysicalMemorySize()) / kb;
ThreadGroup parentThread;
for (parentThread = Thread.currentThread().getThreadGroup(); parentThread.getParent() != null; parentThread = parentThread.getParent());
int totalThread = parentThread.activeCount();
double cpuRatio = 0;
// if (osName.toLowerCase().startsWith("windows")) {
// cpuRatio = this.getCpuRatioForWindows();
// } else {
// cpuRatio = this.getCpuRateForLinux();
// }
MonitorInfoBean infoBean = new MonitorInfoBean();
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);
return infoBean;
}
private static double getCpuRateForLinux() {
InputStream is = null;
InputStreamReader isr = null;
BufferedReader brStat = null;
StringTokenizer tokenStat = null;
try {
System.out.println("Get usage rate of CUP , linux version: " + linuxVersion);
Process process = Runtime.getRuntime().exec("top -b -n 1");
is = process.getInputStream();
isr = new InputStreamReader(is);
brStat = new BufferedReader(isr);
if (linuxVersion.equals("2.4")) {
brStat.readLine();
brStat.readLine();
brStat.readLine();
brStat.readLine();
tokenStat = new StringTokenizer(brStat.readLine());
tokenStat.nextToken();
tokenStat.nextToken();
String user = tokenStat.nextToken();
tokenStat.nextToken();
String system = tokenStat.nextToken();
tokenStat.nextToken();
String nice = 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("%"));
float userUsage = new Float(user).floatValue();
float systemUsage = new Float(system).floatValue();
float niceUsage = new Float(nice).floatValue();
return (userUsage + systemUsage + niceUsage) / 100;
} else {
brStat.readLine();
brStat.readLine();
tokenStat = new StringTokenizer(brStat.readLine());
tokenStat.nextToken();
tokenStat.nextToken();
tokenStat.nextToken();
tokenStat.nextToken();
tokenStat.nextToken();
tokenStat.nextToken();
tokenStat.nextToken();
String cpuUsage = tokenStat.nextToken();
System.out.println("CPU idle : " + cpuUsage);
Float usage = new Float(cpuUsage.substring(0, cpuUsage.indexOf("%")));
return (1 - usage.floatValue() / 100);
}
} catch (IOException ioe) {
System.out.println(ioe.getMessage());
freeResource(is, isr, brStat);
return 1;
} finally {
freeResource(is, isr, brStat);
}
}
private static void freeResource(InputStream is, InputStreamReader isr, BufferedReader br) {
try {
if (is != null)
is.close();
if (isr != null)
isr.close();
if (br != null)
br.close();
} catch (IOException ioe) {
System.out.println(ioe.getMessage());
}
}
private double 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 Double.valueOf(
PERCENT * (busytime) / (busytime + idletime)).doubleValue();
} else {
return 0.0;
}
} catch (Exception ex) {
ex.printStackTrace();
return 0.0;
}
}
private 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;
}
String caption = Bytes.substring(line, capidx, cmdidx - 1) .trim();
String cmd = Bytes.substring(line, cmdidx, kmtidx - 1).trim();
if (cmd.indexOf("wmic.exe") >= 0) {
continue;
}
// log.info("line="+line);
if (caption.equals("System Idle Process") || 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;
return retn;
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
proc.getInputStream().close();
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
public static void main(String[] args) throws Exception {
IMonitorService service = new MonitorServiceImpl();
MonitorInfoBean monitorInfo = service.getMonitorInfoBean();
System.out.println("cpu percent: " + monitorInfo.getCpuRatio());
System.out.println("can use memory: " + monitorInfo.getTotalMemory());
System.out.println("ideal memory: " + monitorInfo.getFreeMemory());
System.out.println("largest memory: " + monitorInfo.getMaxMemory());
System.out.println("all memory: " + monitorInfo.getTotalMemorySize() + "kb");
System.out.println("ideal memory: " + monitorInfo.getFreeMemory() + "kb");
System.out.println("used memory: " + monitorInfo.getUsedMemory() + "kb");
System.out.println("thread num: " + monitorInfo.getTotalThread() + "kb");
}
}
  2.2 执行结果如下图所示:

}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
最新内容请见作者的GitHub页:http://qaseven.github.io/
相关文章
|
10天前
|
机器学习/深度学习 算法 Java
java家政系统实现智能派单?
本项目旨在构建一个基于JAVA的家政系统,通过实时派单满足用户即时需求。系统涵盖用户需求收集、服务人员数据库管理、智能匹配算法(如综合评分、机器学习模型)、实时通信通知、订单状态跟踪及动态调整等功能。同时,优化用户体验,强化安全与隐私保护,并采用微服务架构确保高并发稳定性。通过持续数据分析与算法迭代,实现高效精准的智能派单,提升服务质量和客户满意度。
|
1月前
|
存储 缓存 算法
JVM简介—1.Java内存区域
本文详细介绍了Java虚拟机运行时数据区的各个方面,包括其定义、类型(如程序计数器、Java虚拟机栈、本地方法栈、Java堆、方法区和直接内存)及其作用。文中还探讨了各版本内存区域的变化、直接内存的使用、从线程角度分析Java内存区域、堆与栈的区别、对象创建步骤、对象内存布局及访问定位,并通过实例说明了常见内存溢出问题的原因和表现形式。这些内容帮助开发者深入理解Java内存管理机制,优化应用程序性能并解决潜在的内存问题。
166 29
JVM简介—1.Java内存区域
|
1月前
|
Java 数据库
【YashanDB知识库】kettle同步大表提示java内存溢出
在数据导入导出场景中,使用Kettle进行大表数据同步时出现“ERROR:could not create the java virtual machine!”问题,原因为Java内存溢出。解决方法包括:1) 编辑Spoon.bat增大JVM堆内存至2GB;2) 优化Kettle转换流程,如调整批量大小、精简步骤;3) 合理设置并行线程数(PARALLELISM参数)。此问题影响所有版本,需根据实际需求调整相关参数以避免内存不足。
|
1月前
|
数据可视化 JavaScript Java
2K star!三分钟搭建企业级后台系统,这款开源Java框架绝了!
"LikeAdmin Java是基于Spring Boot + Mybatis Plus + Vue 3的快速开发平台,内置RBAC权限管理、工作流引擎、数据可视化、三方登录等核心模块,助力开发者快速构建企业级中后台管理系统"
123 18
|
1月前
|
前端开发 JavaScript Java
[Java计算机毕设]基于ssm的OA办公管理系统的设计与实现,附源码+数据库+论文+开题,包安装调试
OA办公管理系统是一款基于Java和SSM框架开发的B/S架构应用,适用于Windows系统。项目包含管理员、项目管理人员和普通用户三种角色,分别负责系统管理、请假审批、图书借阅等日常办公事务。系统使用Vue、HTML、JavaScript、CSS和LayUI构建前端,后端采用SSM框架,数据库为MySQL,共24张表。提供完整演示视频和详细文档截图,支持远程安装调试,确保顺利运行。
94 17
|
11天前
|
存储 安全 Java
Java 集合框架详解:系统化分析与高级应用
本文深入解析Java集合框架,涵盖List、Set、Map等核心接口及其常见实现类,如ArrayList、HashSet、HashMap等。通过对比不同集合类型的特性与应用场景,帮助开发者选择最优方案。同时介绍Iterator迭代机制、Collections工具类及Stream API等高级功能,提升代码效率与可维护性。适合初学者与进阶开发者系统学习与实践。
39 0
|
2月前
|
监控 前端开发 Java
构建高效Java后端与前端交互的定时任务调度系统
通过以上步骤,我们构建了一个高效的Java后端与前端交互的定时任务调度系统。该系统使用Spring Boot作为后端框架,Quartz作为任务调度器,并通过前端界面实现用户交互。此系统可以应用于各种需要定时任务调度的业务场景,如数据同步、报告生成和系统监控等。
79 9
|
1月前
|
存储 设计模式 监控
如何快速定位并优化CPU 与 JVM 内存性能瓶颈?
如何快速定位并优化CPU 与 JVM 内存性能瓶颈?
|
2月前
|
存储 IDE Java
java设置栈内存大小
在Java应用中合理设置栈内存大小是确保程序稳定性和性能的重要措施。通过JVM参数 `-Xss`,可以灵活调整栈内存大小,以适应不同的应用场景。本文介绍了设置栈内存大小的方法、应用场景和注意事项,希望能帮助开发者更好地管理Java应用的内存资源。
83 4
java中获取当前系统日期
java中获取当前系统日期

热门文章

最新文章