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

作者:佚名 上传时间:2019-05-27 版权申诉
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/

免责申明:文章和图片全部来源于公开网络,如有侵权,请通知删除 server@dude6.com

用户评论
相关推荐
Java如何获取系统cpu内存硬盘信息
1 概述 前段时间摸索在 Java 中怎么获取系统信息包括cpu、内存、硬盘信息等,刚开始使用Java
Java获取系统CPU内存硬盘系统信息
通过Java程序获取Windows/Linux系统的CPU信息、内存信息、硬盘信息、网络信息、操作系统信息等。
zip
0B
2019-04-29 15:20
获取系统信息cpu内存硬盘网络
获取系统信息的源代码(cpu内存硬盘网络)
RAR
0B
2019-05-22 03:00
VC获取系统信息CPU内存硬盘
主机配置信息主机名,IP,DNS,CPU信息,本进程CPU使用率/主机CPU使用率,本进程内存使用量/主机内存使用量/内存总量,各硬盘的使用量/总量--都能获取,貌似server2008上获取本进程C
RAR
0B
2019-07-14 21:08
如何获取cpu硬盘网卡信息
如何获取cpu、硬盘、mac信息,用来加密软件。
TXT
0B
2018-12-16 13:08
java如何获取系统CPU内存占用
主要介绍了java如何获取系统CPU、内存占用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
PDF
30KB
2020-12-13 07:27
java获取系统信息cpu内存硬盘方法及jar包
java获取系统信息(cpu,内存,硬盘)方法及jar包。还可以直接读出ip地址及使用的网卡。
RAR
0B
2019-05-28 06:55
java获取cpu内存信息
利用java获取电脑的cpu信息、内存信息
RAR
0B
2019-05-20 02:14
Java获取系统信息cpu内存硬盘进程等的相关方法
介绍Java获取系统信息(cpu,内存,硬盘,进程等)的相关方法,其中的代码可以直接拷贝使用,很不错的资源,欢迎下载……
DOC
0B
2019-03-10 17:16
C# 获取本机CPU硬盘内存信息
功能: 1、记录每台服务器(本机)1~24小时的内存使用情况 2、记录每台服务器(本机)CPU负荷使用情况 3、记录每台服务器(本机)磁盘、网络的io流量统计 此程序是没分钟记录一次,然后自动写入Wo
RAR
0B
2018-12-09 18:15