2023年7月3日发(作者:)
java获取系统信息(CPU,内存,硬盘,进程)的相关方法
一、这是一个获取相关信息的简单的方法
import .*;
import ingSystemMXBean;
import mentFactory;
public class Tst{
public static String pt="D:";
public Tst(){
}
public static void main(String[] args) throws Exception{
//free和use和total均为KB
long free=0;
long use=0;
long total=0;
int kb=1024;
Runtime rt=time();
total=emory();
free=mory();
use=total-free;
n("系统内存已用的空间为:"+use/kb+" MB");
n("系统内存的空闲空间为:"+free/kb+" MB");
n("系统总内存空间为:"+total/kb+" MB");
= (OperatingSystemMXBean) OperatingSystemMXBean osmxb
ratingSystemMXBean();
long physicalFree=ePhysicalMemorySize()/kb;
long physicalTotal=alPhysicalMemorySize()/kb;
long physicalUse=physicalTotal-physicalFree;
String os=perty("");
n("操作系统的版本:"+os);
n("系统物理内存已用的空间为:"+physicalFree+" MB");
n("系统物理内存的空闲空间为:"+physicalUse+" MB");
n("总物理内存:"+physicalTotal+" MB");
// 获得线程总数
ThreadGroup parentThread;
for (parentThread = tThread().getThreadGroup(); parentThread
.getParent() != null; parentThread = ent())
;
int totalThread = Count();
n("获得线程总数:"+totalThread);
}
二,别的方法技巧
} 1.利用jdk自带的API获取信息:(只支持jdk1.60以上的版本啊)
import treamReader;
import mberReader;
import ist;
import ;
import ingSystemMXBean;
import ;
import mentFactory;
/**
* 获取windows系统信息(CPU,内存,文件系统)
* @author libing
*
*/
public class WindowsInfoUtil {
private static final int CPUTIME = 500;
private static final int PERCENT = 100;
private static final int FAULTLENGTH = 10;
public static void main(String[] args) {
n(getCpuRatioForWindows());
n(getMemery());
n(getDisk());
}
//获取内存使用率
public static String getMemery(){
OperatingSystemMXBean osmxb = (OperatingSystemMXBean)
ratingSystemMXBean();
// 总的物理内存+虚拟内存
long totalvirtualMemory = alSwapSpaceSize();
// 剩余的物理内存
long freePhysicalMemorySize = ePhysicalMemorySize();
Double compare=(Double)(1-freePhysicalMemorySize*1.0/totalvirtualMemory)*100;
String str="内存已使用:"+ue()+"%";
return str;
}
//获取文件系统使用率
public static List
// 操作系统
List
for (char c = 'A'; c <= 'Z'; c++) {
String dirName = c + ":/";
File win = new File(dirName);
if(()){
long total=(long)alSpace();
long free=(long)eSpace();
Double compare=(Double)(1-free*1.0/total)*100;
String str=c+":盘 已使用 "+ue()+"%";
(str);
}
}
return list;
}
//获得cpu使用率
public static String getCpuRatioForWindows() {
try {
String procCmd = ("windir") + "
process get
Caption,CommandLine,KernelModeTime,ReadOperationCount,ThreadCount,UserModeTime,WriteOperationCount";
// 取进程信息
long[] c0 = readCpu(time().exec(procCmd));
(CPUTIME);
long[] c1 = readCpu(time().exec(procCmd));
if (c0 != null && c1 != null) {
long idletime = c1[0] - c0[0];
long busytime = c1[1] - c0[1];
return "CPU使用率:"+f(PERCENT * (busytime)*1.0 / (busytime
+ idletime)).intValue()+"%";
} else {
return "CPU使用率:"+0+"%";
}
} catch (Exception ex) {
tackTrace();
return "CPU使用率:"+0+"%";
}
}
//读取cpu相关信息
private static long[] readCpu(final Process proc) {
long[] retn = new long[2];
try {
putStream().close();
InputStreamReader ir = new InputStreamReader(utStream());
LineNumberReader input = new LineNumberReader(ir);
String line = ne();
if (line == null || () < FAULTLENGTH) {
return null;
}
int capidx = f("Caption");
int cmdidx = f("CommandLine");
int rocidx = f("ReadOperationCount");
int umtidx = f("UserModeTime");
int kmtidx = f("KernelModeTime");
int wocidx = f("WriteOperationCount");
long idletime = 0;
long kneltime = 0;
long usertime = 0;
while ((line = ne()) != null) {
if (() < 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 (f("") >= 0) {
continue;
}
String s1 = substring(line, kmtidx, rocidx - 1).trim();
String s2 = substring(line, umtidx, wocidx - 1).trim();
if (("System Idle Process") || ("System")) {
if (() > 0)
idletime += f(s1).longValue();
if (() > 0)
idletime += f(s2).longValue();
continue;
}
if (() > 0)
kneltime += f(s1).longValue();
if (() > 0)
usertime += f(s2).longValue();
}
retn[0] = idletime;
retn[1] = kneltime + usertime;
return retn;
} catch (Exception ex) {
tackTrace();
} finally {
try {
utStream().close();
} catch (Exception e) {
tackTrace();
}
}
return null;
}
/**
* 由于ing对汉字处理存在问题(把一个汉字视为一个字节),因此在 包含汉字的字符串时存在隐患,现调整如下:
* @param src 要截取的字符串
* @param start_idx 开始坐标(包括该坐标)
* @param end_idx 截止坐标(包括该坐标)
* @return
*/
private static String substring(String src, int start_idx, int end_idx) {
byte[] b = es();
String tgt = "";
for (int i = start_idx; i <= end_idx; i++) {
tgt += (char) b[i];
}
return tgt;
}
}
2.利用第三方的jar包:(Hyperic-hq官方网站:)
通过Hyperic-hq产品的基础包来实现服务器状态数据的获取。包是通过本地方法来调用操作系统API来 获取系统相关数据。Windows操作系统下依赖或sigar-x86- ,linux 操作系统下则依赖或
import dress;
import nHostException;
import o;
import c;
import stem;
import stemUsage;
import ;
import gs;
import erfaceConfig;
import erfaceStat;
import ingSystem;
import ;
import xception;
import otImplementedException;
import ;
public class SysInfo {
// 资源信息
// a)CPU数量(单位:个)
public static int getCpuCount() throws SigarException {
Sigar sigar = new Sigar();
try {
return InfoList().length;
} finally {
();
}
}
// b)CPU的总量(单位:HZ)及CPU的相关信息
public void getCpuTotal() {
Sigar sigar = new Sigar();
CpuInfo[] infos;
try {
infos = InfoList();
for (int i = 0; i < ; i++) {// 不管是单块CPU还是多CPU都适用
CpuInfo info = infos[i];
n("mhz=" + ());// CPU的总量MHz
n("vendor=" + dor());// 获得CPU的卖主,如:Intel
n("model=" + el());// 获得CPU的类别,如:Celeron
n("cache size=" + heSize());// 缓冲存储器数量
}
} catch (SigarException e) {
tackTrace();
}
}
// c)CPU的用户使用量、系统使用剩余量、总的剩余量、总的使用占用量等(单位:100%)
public void testCpuPerc() {
Sigar sigar = new Sigar();
// 方式一,主要是针对一块CPU的情况
CpuPerc cpu;
try {
cpu = Perc();
printCpuPerc(cpu);
} catch (SigarException e) {
tackTrace();
}
// 方式二,不管是单块CPU还是多CPU都适用
CpuPerc cpuList[] = null;
try {
cpuList = PercList();
} catch (SigarException e) {
tackTrace();
return;
}
for (int i = 0; i < ; i++) {
printCpuPerc(cpuList[i]);
}
}
private void printCpuPerc(CpuPerc cpu) {
n("User :" + (r()));// 用户使用率
n("Sys :" + (()));// 系统使用率
n("Wait :" + (t()));// 当前等待率
n("Nice :" + (e()));//
n("Idle :" + (e()));// 当前空闲率
n("Total :" + (bined()));// 总的使用率
}
// 2.内存资源信息
public void getPhysicalMemory() {
// a)物理内存信息
Sigar sigar = new Sigar();
Mem mem;
try {
mem = ();
// 内存总量
n("Total = " + al() / 1024L + "K av");
// 当前内存使用量
n("Used = " + d() / 1024L + "K used");
// 当前内存剩余量
n("Free = " + e() / 1024L + "K free");
// b)系统页面文件交换区信息
Swap swap = p();
// 交换区总量
n("Total = " + al() / 1024L + "K av");
// 当前交换区使用量
n("Used = " + d() / 1024L + "K used");
// 当前交换区剩余量
n("Free = " + e() / 1024L + "K free");
} catch (SigarException e) {
tackTrace();
}
}
// 3.操作系统信息
// a)取到当前操作系统的名称:
public String getPlatformName() {
String hostname = "";
try {
hostname = alHost().getHostName();
} catch (Exception exc) {
Sigar sigar = new Sigar();
try {
hostname = Info().getHostName();
} catch (SigarException e) {
hostname = "n";
} finally {
();
}
}
return hostname;
}
// b)取当前操作系统的信息
public void testGetOSInfo() {
OperatingSystem OS = tance();
// 操作系统内核类型如: 386、486、586等x86
n("h() = " + h());
n("Endian() = " + Endian());//
n("aModel() = " + aModel());//
// 系统描述
n("cription() = " + cription());
n("hine() = " + hine());//
// 操作系统类型
n("e() = " + e());
n("chLevel() = " + chLevel());//
// 操作系统的卖主
n("dor() = " + dor());
// 卖主名称
.println("dorCodeName() = " + dorCodeName());
// 操作系统名称
n("dorName() = " + dorName());
// 操作系统卖主类型
n("dorVersion() = " + dorVersion());
// 操作系统的版本号
n("sion() = " + sion());
}
// c)取当前系统进程表中的用户信息
public void testWho() {
try {
Sigar sigar = new Sigar();
[] who = List();
if (who != null && > 0) {
for (int i = 0; i < ; i++) {
n("n~~~~~~~~~" + f(i)+ "~~~~~~~~~");
_who = who[i];
n("getDevice() = " + _ice());
n("getHost() = " + _t());
n("getTime() = " + _e());
// 当前系统进程表中的用户名
n("getUser() = " + _r());
}
}
} catch (SigarException e) {
tackTrace();
}
}
// 4.资源信息(主要是硬盘)
// a)取硬盘已有的分区及其详细信息(通过eSystemList()来获得FileSystem列表对象,然后对其进行编历):
public void testFileSystemInfo() throws Exception {
Sigar sigar = new Sigar();
FileSystem fslist[] = eSystemList();
//String dir = perty("");// 当前用户文件夹路径
for (int i = 0; i < ; i++) {
n("n~~~~~~~~~~" + i + "~~~~~~~~~~");
FileSystem fs = fslist[i];
// 分区的盘符名称
n("Name() = " + Name());
// 分区的盘符名称
n("Name() = " + Name());
n("gs() = " + gs());//
// 文件系统类型,比如 FAT32、NTFS
n("TypeName() = " + TypeName());
// 文件系统类型名,比如本地硬盘、光驱、网络文件系统等
n("eName() = " + eName());
// 文件系统类型
n("e() = " + e());
FileSystemUsage usage = null;
try {
usage = eSystemUsage(Name());
} catch (SigarException e) {
if (e() == 2)
throw e;
continue;
}
switch (e()) {
case 0: // TYPE_UNKNOWN :未知
break;
case 1: // TYPE_NONE
break;
case 2: // TYPE_LOCAL_DISK : 本地硬盘
// 文件系统总大小
n(" Total = " + al() + "KB");
// 文件系统剩余大小
n(" Free = " + e() + "KB");
// 文件系统可用大小
n(" Avail = " + il() + "KB");
// 文件系统已经使用量
n(" Used = " + d() + "KB");
double usePercent = Percent() * 100D;
// 文件系统资源的利用率
n(" Usage = " + usePercent + "%");
break;
case 3:// TYPE_NETWORK :网络
break;
case 4:// TYPE_RAM_DISK :闪存
break;
case 5:// TYPE_CDROM :光驱
break;
case 6:// TYPE_SWAP :页面交换
break;
}
n(" DiskReads = " + kReads());
n(" DiskWrites = " + kWrites());
}
return;
}
// 5.网络信息
// a)当前机器的正式域名
public String getFQDN() {
Sigar sigar = null;
try {
return alHost().getCanonicalHostName();
} catch (UnknownHostException e) {
try {
sigar = new Sigar();
return N();
} catch (SigarException ex) {
return null;
} finally {
();
}
}
}
// b)取到当前机器的IP地址
public String getDefaultIpAddress() {
String address = null;
try {
address = alHost().getHostAddress();
// 没有出现异常而正常当取到的IP时,如果取到的不是网卡循回地址时就返回
// 否则再通过Sigar工具包中的方法来获取
if (!CK_(address)) {
return address;
}
} catch (UnknownHostException e) {
// hostname not in DNS or /etc/hosts
}
Sigar sigar = new Sigar();
try {
address = InterfaceConfig().getAddress();
} catch (SigarException e) {
address = CK_ADDRESS;
} finally {
();
}
return address;
}
// c)取到当前机器的MAC地址
public String getMAC() {
Sigar sigar = null;
try {
sigar = new Sigar();
String[] ifaces = InterfaceList();
String hwaddr = null;
for (int i = 0; i < ; i++) {
NetInterfaceConfig cfg = InterfaceConfig(ifaces[i]);
if (CK_(ress())
|| (gs() & _LOOPBACK) != 0
|| _(ddr())) {
continue;
}
/*
* 如果存在多张网卡包括虚拟机的网卡,默认只取第一张网卡的MAC地址,如果要返回所有的网卡(包括物理的和虚拟的)则可以修改方法的返回类型为数组或Collection
* ,通过在for循环里取到的多个MAC地址。
*/
hwaddr = ddr();
break;
}
return hwaddr != null ? hwaddr : null;
} catch (Exception e) {
return null;
} finally {
if (sigar != null)
();
}
}
// d)获取网络流量等信息
public void testNetIfList() throws Exception {
Sigar sigar = new Sigar();
String ifNames[] = InterfaceList();
for (int i = 0; i < ; i++) {
String name = ifNames[i];
NetInterfaceConfig ifconfig = InterfaceConfig(name);
print("nname = " + name);// 网络设备名
print("Address = " + ress());// IP地址
print("Netmask = " + mask());// 子网掩码
if ((gs() & 1L) <= 0L) {
print("!skipping getNetInterfaceStat");
continue;
}
try {
NetInterfaceStat ifstat = InterfaceStat(name);
print("RxPackets = " + ackets());// 接收的总包裹数
print("TxPackets = " + ackets());// 发送的总包裹数
print("RxBytes = " + ytes());// 接收到的总字节数
print("TxBytes = " + ytes());// 发送的总字节数
print("RxErrors = " + rrors());// 接收到的错误包数
print("TxErrors = " + rrors());// 发送数据包时的错误数
print("RxDropped = " + ropped());// 接收时丢弃的包数
print("TxDropped = " + ropped());// 发送时丢弃的包数
} catch (SigarNotImplementedException e) {
} catch (SigarException e) {
print(sage());
}
}
}
void print(String msg) {
n(msg);
}
// e)一些其他的信息
public void getEthernetInfo() {
Sigar sigar = null;
try {
sigar = new Sigar();
String[] ifaces = InterfaceList();
for (int i = 0; i < ; i++) {
NetInterfaceConfig cfg = InterfaceConfig(ifaces[i]);
if (CK_(ress())
|| (gs() & _LOOPBACK) != 0
|| _(ddr())) {
continue;
}
n("ress() = " + ress());// IP地址
.println("adcast() = " + adcast());// 网关广播地址
n("ddr() = " + ddr());// 网卡MAC地址
n("mask() = " + mask());// 子网掩码
n("cription() = "
+ cription());// 网卡描述信息
n("e() = " + e());//
n("tination() = "
+ tination());
n("gs() = " + gs());//
n("ric() = " + ric());
n("() = " + ());
n("e() = " + e());
n();
}
} catch (Exception e) {
n("Error while creating GUID" + e);
} finally {
if (sigar != null)
();
}
}
}
发布者:admin,转转请注明出处:http://www.yc00.com/news/1688329553a121137.html
评论列表(0条)