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/
相关文章
|
18天前
|
算法 程序员
深入理解操作系统内存管理:分页系统的优势与挑战
【4月更文挑战第7天】 在现代操作系统中,内存管理是一项至关重要的任务,它确保了计算机能够高效、安全地运行各种程序。分页系统作为内存管理的一种技术,通过将物理内存分割成固定大小的单元——页面,为每个运行的程序提供了一种独立且连续的内存地址空间。该技术不仅简化了内存分配,还允许更高效的内存使用和保护。本文探讨了分页系统的核心原理,优势以及面临的挑战,旨在为读者揭示其在操作系统设计中的重要性。
|
1月前
|
Java
有关Java发送邮件信息(支持附件、html文件模板发送)
有关Java发送邮件信息(支持附件、html文件模板发送)
31 1
|
16天前
|
Linux
centos 查看服务器信息 版本cpu
centos 查看服务器信息 版本cpu
12 0
|
18天前
|
Prometheus 监控 Cloud Native
【Linux】查看系统内存命令(详细讲解)
【Linux】查看系统内存命令(详细讲解)
|
30天前
|
存储 缓存 监控
Linux 系统 内存通用指标以及查询方式
Linux 系统 内存通用指标以及查询方式
18 0
|
30天前
|
存储 监控 Linux
Linux 使用getrusage系统调用获取cpu信息:一个C++实例分析
Linux 使用getrusage系统调用获取cpu信息:一个C++实例分析
49 0
|
1月前
|
存储 缓存 Shell
【Shell 命令集合 系统管理 】⭐⭐⭐Linux 显示系统内存的使用情况 free命令 使用指南
【Shell 命令集合 系统管理 】⭐⭐⭐Linux 显示系统内存的使用情况 free命令 使用指南
29 0
|
1月前
|
缓存 算法 安全
深入理解操作系统内存管理:分页系统的优势与挑战
【2月更文挑战第30天】 在现代操作系统中,内存管理是核心功能之一,它负责将有限的物理内存资源分配给多个并发运行的进程。分页系统作为内存管理的一种流行技术,其通过虚拟到物理地址的映射提供了程序的逻辑地址空间,并允许更高效的内存分配和保护。本文旨在探讨分页系统的关键优势,包括其如何提升内存利用率、实现内存保护以及支持多任务处理。同时,我们也将分析分页机制带来的挑战,诸如页面置换算法的效率问题、页表管理和TLB(Translation Lookaside Buffer)的维护等。
|
1月前
|
JSON Java Serverless
nacos常见问题之cpu和内存占用高如何解决
Nacos是阿里云开源的服务发现和配置管理平台,用于构建动态微服务应用架构;本汇总针对Nacos在实际应用中用户常遇到的问题进行了归纳和解答,旨在帮助开发者和运维人员高效解决使用Nacos时的各类疑难杂症。
181 0
|
2月前
|
弹性计算
2024阿里云幻兽帕鲁/Palworld服务器价格表(CPU/内存/带宽/磁盘收费标准)
2024年阿里云幻兽帕鲁专用服务器的价格根据不同的配置有所不同。 • 4核16G配置的价格为32元/月,如果选择购买3个月,则价格为96元。 • 8核32G配置的价格为90元/月,如果选择购买3个月,则价格为271元。 另外,还有配置为4核16G10M带宽的服务器,其价格为26元/月起。而8核32G10M带宽的价格也是90元/月。
96 1

热门文章

最新文章