先说怎么使用Sigar,
1.在官网下载Sigar文件包
2.解压出来,进入到sigar-bin/lib文件夹里面
3.把lib里面东西全加到工程lib包里面4.把lib文件夹里面的Sigar.jar添加到工程里面
5.可以使用了
下面是代码,需要的各种基本数据都获取到了,CPU,内存,硬盘,网络方面
package sigar;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.DecimalFormat;
import org.hyperic.sigar.CpuInfo;
import org.hyperic.sigar.CpuPerc;
import org.hyperic.sigar.FileSystem;
import org.hyperic.sigar.FileSystemUsage;
import org.hyperic.sigar.Mem;
import org.hyperic.sigar.NetFlags;
import org.hyperic.sigar.NetInterfaceConfig;
import org.hyperic.sigar.NetInterfaceStat;
import org.hyperic.sigar.OperatingSystem;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.SigarNotImplementedException;
import org.hyperic.sigar.Swap;
public class SystemInfo {
public static void main(String[] args) throws Exception{
SystemInfo s = new SystemInfo();
System.out.println("CPU个数: " + s.getCpuCount());
s.getCpuTotal();
s.getPhyssicalMemory();
s.getplatformName();
s.getDefaultIpAddress();
s.getEthernetInfo();
s.getFQDN();
s.getMAC();
s.testWho();
s.testFileSystemInfo();
s.testGetOSInfo();
s.testNetIfList();
s.testCpuPerc();
}
/**
* 1.CPU资源信息
* @return
*/
//CPU个数(单位:个)
public int getCpuCount() throws SigarException{
Sigar sigar = new Sigar();
try{
System.out.println("CPU个数: ");
return sigar.getCpuInfoList().length; //返回CPU的个数
}finally{
sigar.close();
}
}
/**
* CPU的总量(单位:MHz)以及CPU的相关信息
* @throws SigarException
*/
public void getCpuTotal(){
Sigar sigar = new Sigar();
CpuInfo[] infos;
try{
infos =sigar.getCpuInfoList();
for(int i = 0; i < infos.length; i++){// 不管是单块CPU还是多CPU都适用
CpuInfo cpuInfo = infos[i];
int cpuMhz = cpuInfo.getMhz(); //CPU的总量MHz
String cpuVendor = cpuInfo.getVendor(); // CPU的生产厂家,如:Intel
String cpuModel = cpuInfo.getVendor();//CPU的类别如:celeron
long cpuCacheSize = cpuInfo.getCacheSize(); //缓冲存储器数量
System.out.println("CPU的总量:" + cpuMhz);
System.out.println("CPU生产厂家:" + cpuVendor);
System.out.println("CPU的类别:" + cpuModel);
System.out.println("缓冲存储器的数量:" + cpuCacheSize);
System.out.println("================================");
}
}catch(SigarException e){
e.printStackTrace();
}
}
/**
* CPU的用户使用量、系统使用剩余量、总的剩余量、总的使用占用量等(单位:100%)
*/
public void testCpuPerc(){
Sigar sigar = new Sigar();
//单CPU或者多CPU都适用
CpuPerc cpuList[] = null;
try {
cpuList = sigar.getCpuPercList();
} catch (SigarException e) {
e.printStackTrace();
return;
}
for(int i = 0; i< cpuList.length; i++){
printCpuPerc(cpuList[i]); //用于打印cpu的使用情况
}
}
//打印cpu的使用率
private void printCpuPerc(CpuPerc cpuPerc) {
String cpuPercUser = CpuPerc.format(cpuPerc.getUser());// 用户使用率
String cpuPercSys = CpuP