Java获取硬件信息
不同操作系统需要的jar包
- linux 64 bit ---------- libsigar-amd64-linux.so
- linux 32 bit ---------- libsigar-x86-linux.so
- windows 64 bit ---------- sigar-amd64-winnt.dll
- windows 32 bit ---------- sigar-x86-winnt.dll
初始化sigar的服务
@Component
public class InitServlet implements InitializingBean {
@Override
public void afterPropertiesSet() throws Exception {
try {
String osName = System.getProperty("os.name").toLowerCase();
if (null != osName && -1 < osName.indexOf("linux")) {
if (System.getProperty("os.arch").indexOf("64") != -1) {
String path=InitServlet.class.getResource("/").getPath().toString();
System.load(path+"libsigar-amd64-linux.so");
} else {
String path=InitServlet.class.getResource("/").getPath().toString();
System.load(path+"libsigar-x86-linux.so");
}
} else {
//暂时注释掉想到其他方法再解决
if (System.getenv("ProgramFiles(x86)") != null){
String path=InitServlet.class.getResource("/").getPath().toString();
System.load(path+"sigar-amd64-winnt.dll");
} else {
String path=InitServlet.class.getResource("/").getPath().toString();
System.load(path+"sigar-x86-winnt.dll");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
获取硬件信息举例
public static Map<String, Long> getPerformanceInfoUbuntu() {
Sigar sigar = null ;
Map<String, Long> map = new HashMap<String, Long>();
try {
sigar = new Sigar();
CpuInfo []infos = sigar.getCpuInfoList();
long totalCpuNum=infos.length; //总核数
long totalCpuMhz=0; //总赫兹数
for (int i = 0; i < infos.length; i++) {// 不管是单块CPU还是多CPU都适用
CpuInfo info = infos[i];
totalCpuMhz+=info.getMhz();
}
map.put("success", Long.parseLong("1"));
map.put("totalCpuNum", totalCpuNum);
map.put("totalCpuMhz", totalCpuMhz);
} catch (SigarException e) {
map.put("success", Long.parseLong("0"));
e.printStackTrace();
} finally {
if (sigar != null){
try {
sigar.close();
sigar = null;
} catch (Exception e) {
e.printStackTrace();
} finally {
sigar = null;
}
}
}
return map;
}