A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

Java获取系统信息(cpu,内存,硬盘,进程等)的相关方法
1利用jdk自带的API获取信息

(只支持jdk1.60以上的版本啊)
1 import java.io.InputStreamReader;
2 import java.io.LineNumberReader;
3 import java.util.ArrayList;
4 import java.util.List;
5 import mytools.com.sun.management.OperatingSystemMXBean;
6 import mytools.java.io.File;
7 import mytools.java.lang.management.ManagementFactory;
8 /**
9 * 获取windows系统信息(CPU,内存,文件系统)
10 * @author libing
11 *
12 */
13 public class WindowsInfoUtil {
14 private static final int CPUTIME = 500;
15 private static final int PERCENT = 100;
16 private static final int FAULTLENGTH = 10;
17  
18 public static void main(String[] args) {
19  
20 System.out.println(getCpuRatioForWindows());
21 System.out.println(getMemery());
22 System.out.println(getDisk());
23 }
24  
25 //获取内存使用率
26 public static String getMemery(){
27  
28 OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
29  
30 // 总的物理内存+虚拟内存
31  
32 long totalvirtualMemory = osmxb.getTotalSwapSpaceSize();
33 // 剩余的物理内存
34 long freePhysicalMemorySize = osmxb.getFreePhysicalMemorySize();
35  
36 Double compare=(Double)(1-freePhysicalMemorySize*1.0/totalvirtualMemory)*100;
37  
38 String str="内存已使用:"+compare.intValue()+"%";
39  
40 return str;
41 }
42  
43  
44 //获取文件系统使用率
45  
46 public static List<String> getDisk() {
47  
48 // 操作系统
49  
50 List<String> list=new ArrayList<String>();
51  
52 for (char c = 'A'; c <= 'Z'; c++) {
53  
54 String dirName = c + ":/";
55  
56 File win = new File(dirName);
57  
58 if(win.exists()){
59  
60 long total=(long)win.getTotalSpace();
61  
62 long free=(long)win.getFreeSpace();
63  
64 Double compare=(Double)(1-free*1.0/total)*100;
65  
66 String str=c+":盘 已使用 "+compare.intValue()+"%";
67  
68 list.add(str);
69 }
70  
71 }
72  
73 return list;
74  
75 }
76  
77  
78 //获得cpu使用率
79  
80 public static String getCpuRatioForWindows() {
81 try {
82  
83 String procCmd = System.getenv("windir") + "//system32//wbem//wmic.exe process get Caption,CommandLine,KernelModeTime,ReadOperationCount,ThreadCount,UserModeTime,WriteOperationCount";
84  
85 // 取进程信息
86  
87 long[] c0 = readCpu(Runtime.getRuntime().exec(procCmd));
88  
89 Thread.sleep(CPUTIME);
90  
91 long[] c1 = readCpu(Runtime.getRuntime().exec(procCmd));
92  
93 if (c0 != null && c1 != null) {
94  
95 long idletime = c1[0] - c0[0];
96  
97 long busytime = c1[1] - c0[1];
98  
99 return "CPU使用率:"+Double.valueOf(PERCENT * (busytime)*1.0 / (busytime + idletime)).intValue()+"%";
100 } else {
101 return "CPU使用率:"+0+"%";
102 }
103 } catch (Exception ex) {
104 ex.printStackTrace();
105 return "CPU使用率:"+0+"%";
106 }
107 }
108  
109 //读取cpu相关信息
110  
111 private static long[] readCpu(final Process proc) {
112  
113 long[] retn = new long[2];
114  
115 try {
116  
117 proc.getOutputStream().close();
118  
119 InputStreamReader ir = new InputStreamReader(proc.getInputStream());
120  
121 LineNumberReader input = new LineNumberReader(ir);
122  
123 String line = input.readLine();
124  
125 if (line == null || line.length() < FAULTLENGTH) {
126  
127 return null;
128 }
129 int capidx = line.indexOf("Caption");
130 int cmdidx = line.indexOf("CommandLine");
131 int rocidx = line.indexOf("ReadOperationCount");
132 int umtidx = line.indexOf("UserModeTime");
133 int kmtidx = line.indexOf("KernelModeTime");
134 int wocidx = line.indexOf("WriteOperationCount");
135 long idletime = 0;
136 long kneltime = 0;
137 long usertime = 0;
138 while ((line = input.readLine()) != null) {
139 if (line.length() < wocidx) {
140 continue;
141 }
142  
143 // 字段出现顺序:Caption,CommandLine,KernelModeTime,ReadOperationCount,
144 // ThreadCount,UserModeTime,WriteOperation
145 String caption =substring(line, capidx, cmdidx - 1).trim();
146 String cmd = substring(line, cmdidx, kmtidx - 1).trim();
147 if (cmd.indexOf("wmic.exe") >= 0) {
148 continue;
149 }
150 String s1 = substring(line, kmtidx, rocidx - 1).trim();
151 String s2 = substring(line, umtidx, wocidx - 1).trim();
152 if (caption.equals("System Idle Process") || caption.equals("System")) {
153 if (s1.length() > 0)
154 idletime += Long.valueOf(s1).longValue();
155 if (s2.length() > 0)
156 idletime += Long.valueOf(s2).longValue();
157 continue;
158 }
159 if (s1.length() > 0)
160 kneltime += Long.valueOf(s1).longValue();
161 if (s2.length() > 0)
162 usertime += Long.valueOf(s2).longValue();
163 }
164 retn[0] = idletime;
165 retn[1] = kneltime + usertime;
166 return retn;
167 } catch (Exception ex) {
168 ex.printStackTrace();
169 } finally {
170 try {
171 proc.getInputStream().close();
172 } catch (Exception e) {
173 e.printStackTrace();
174 }
175 }
176 return null;
177 }
178 /**
179 * 由于String.subString对汉字处理存在问题(把一个汉字视为一个字节),因此在 包含汉字的字符串时存在隐患,现调整如下:
180 * @param src 要截取的字符串
181 * @param start_idx 开始坐标(包括该坐标)
182 * @param end_idx 截止坐标(包括该坐标)
183 * @return
184 */
185  
186 private static String substring(String src, int start_idx, int end_idx) {
187 byte[] b = src.getBytes();
188 String tgt = "";
189 for (int i = start_idx; i <= end_idx; i++) {
190 tgt += (char) b;
191 }
192 return tgt;
193 }
194 }
2利用第三方的jar

Hyperic-hq官方网站:http://www.hyperic.com
通过Hyperic-hq产品的基础包sigar.jar来实现服务器状态数据的获取。Sigar.jar包是通过本地方法来调用操作系统API来获取系统相关数据。Windows操作系统下Sigar.jar依赖sigar-amd64-winnt.dll或sigar-x86-winnt.dll,linux 操作系统下则依赖libsigar-amd64-linux.so或libsigar-x86-linux.so
195 import java.net.InetAddress;
196 import java.net.UnknownHostException;
197 import org.hyperic.sigar.CpuInfo;
198 import org.hyperic.sigar.CpuPerc;
199 import org.hyperic.sigar.FileSystem;
200 import org.hyperic.sigar.FileSystemUsage;
201 import org.hyperic.sigar.Mem;
202 import org.hyperic.sigar.NetFlags;
203 import org.hyperic.sigar.NetInterfaceConfig;
204 import org.hyperic.sigar.NetInterfaceStat;
205 import org.hyperic.sigar.OperatingSystem;
206 import org.hyperic.sigar.Sigar;
207 import org.hyperic.sigar.SigarException;
208 import org.hyperic.sigar.SigarNotImplementedException;
209 import org.hyperic.sigar.Swap;
210
211 public class SysInfo {
212 // 1.CPU资源信息
213 // a)CPU数量(单位:个)
214 public static int getCpuCount() throws SigarException {
215 Sigar sigar = new Sigar();
216 try {
217 return sigar.getCpuInfoList().length;
218 } finally {
219 sigar.close();
220 }
221 }
222
223 // b)CPU的总量(单位:HZ)及CPU的相关信息
224 public void getCpuTotal() {
225 Sigar sigar = new Sigar();
226 CpuInfo[] infos;
227 try {
228 infos = sigar.getCpuInfoList();
229 for (int i = 0; i < infos.length; i++) {// 不管是单块CPU还是多CPU都适用
230 CpuInfo info = infos;
231 System.out.println("mhz=" + info.getMhz());// CPU的总量MHz
232 System.out.println("vendor=" + info.getVendor());// 获得CPU的卖主,如:Intel
233 System.out.println("model=" + info.getModel());// 获得CPU的类别,如:Celeron
234 System.out.println("cache size=" + info.getCacheSize());// 缓冲存储器数量
235 }
236 } catch (SigarException e) {
237 e.printStackTrace();
238 }
239 }
240 // c)CPU的用户使用量、系统使用剩余量、总的剩余量、总的使用占用量等(单位:100%
241 public void testCpuPerc() {
242 Sigar sigar = new Sigar();
243 // 方式一,主要是针对一块CPU的情况
244 CpuPerc cpu;
245 try {
246 cpu = sigar.getCpuPerc();
247 printCpuPerc(cpu);
248 } catch (SigarException e) {
249 e.printStackTrace();
250 }
251 // 方式二,不管是单块CPU还是多CPU都适用
252 CpuPerc cpuList[] = null;
253 try {
254 cpuList = sigar.getCpuPercList();
255 } catch (SigarException e) {
256 e.printStackTrace();
257 return;
258 }
259 for (int i = 0; i < cpuList.length; i++) {
260 printCpuPerc(cpuList);
261 }
262 }
263 private void printCpuPerc(CpuPerc cpu) {
264 System.out.println("User :" + CpuPerc.format(cpu.getUser()));// 用户使用率
265
266 System.out.println("Sys :" + CpuPerc.format(cpu.getSys()));// 系统使用率
267
268 System.out.println("Wait :" + CpuPerc.format(cpu.getWait()));// 当前等待率
269
270 System.out.println("Nice :" + CpuPerc.format(cpu.getNice()));//
271 System.out.println("Idle :" + CpuPerc.format(cpu.getIdle()));// 当前空闲率
272
273 System.out.println("Total :" + CpuPerc.format(cpu.getCombined()));// 总的使用率
274 }
275 // 2.内存资源信息
276 public void getPhysicalMemory() {
277 // a)物理内存信息
278 Sigar sigar = new Sigar();
279 Mem mem;
280
281 try {
282
283 mem = sigar.getMem();
284
285 // 内存总量
286 System.out.println("Total = " + mem.getTotal() / 1024L + "K av");
287 // 当前内存使用量
288 System.out.println("Used = " + mem.getUsed() / 1024L + "K used");
289 // 当前内存剩余量
290 System.out.println("Free = " + mem.getFree() / 1024L + "K free");
291
292 // b)系统页面文件交换区信息
293 Swap swap = sigar.getSwap();
294 // 交换区总量
295 System.out.println("Total = " + swap.getTotal() / 1024L + "K av");
296 // 当前交换区使用量
297 System.out.println("Used = " + swap.getUsed() / 1024L + "K used");
298 // 当前交换区剩余量
299 System.out.println("Free = " + swap.getFree() / 1024L + "K free");
300 } catch (SigarException e) {
301 e.printStackTrace();
302 }
303
304
305 }
306 // 3.操作系统信息
307 // a)取到当前操作系统的名称:
308 public String getPlatformName() {
309 String hostname = "";
310 try {
311 hostname = InetAddress.getLocalHost().getHostName();
312 } catch (Exception exc) {
313 Sigar sigar = new Sigar();
314 try {
315 hostname = sigar.getNetInfo().getHostName();
316 } catch (SigarException e) {
317 hostname = "localhost.unknown";
318 } finally {
319 sigar.close();
320 }
321 }
322 return hostname;
323 }
324 // b)取当前操作系统的信息
325 public void testGetOSInfo() {
326 OperatingSystem OS = OperatingSystem.getInstance();
327 // 操作系统内核类型如: 386486586x86
328 System.out.println("OS.getArch() = " + OS.getArch());
329 System.out.println("OS.getCpuEndian() = " + OS.getCpuEndian());//
330 System.out.println("OS.getDataModel() = " + OS.getDataModel());//
331 // 系统描述
332 System.out.println("OS.getDescription() = " + OS.getDescription());
333 System.out.println("OS.getMachine() = " + OS.getMachine());//
334 // 操作系统类型
335
336
337 System.out.println("OS.getName() = " + OS.getName());
338
339
340 System.out.println("OS.getPatchLevel() = " + OS.getPatchLevel());//
341
342
343 // 操作系统的卖主
344
345
346 System.out.println("OS.getVendor() = " + OS.getVendor());
347
348
349 // 卖主名称
350
351
352 System.out
353
354
355 .println("OS.getVendorCodeName() = " + OS.getVendorCodeName());
356
357
358 // 操作系统名称
359
360
361 System.out.println("OS.getVendorName() = " + OS.getVendorName());
362
363
364 // 操作系统卖主类型
365
366
367 System.out.println("OS.getVendorVersion() = " + OS.getVendorVersion());
368
369
370 // 操作系统的版本号
371 System.out.println("OS.getVersion() = " + OS.getVersion());
372 }
373 // c)取当前系统进程表中的用户信息
374 public void testWho() {
375 try {
376 Sigar sigar = new Sigar();
377 org.hyperic.sigar.Who[] who = sigar.getWhoList();
378 if (who != null && who.length > 0) {
379 for (int i = 0; i < who.length; i++) {
380 System.out.println("/n~~~~~~~~~" + String.valueOf(i)+ "~~~~~~~~~");
381 org.hyperic.sigar.Who _who = who;
382 System.out.println("getDevice() = " + _who.getDevice());
383 System.out.println("getHost() = " + _who.getHost());
384 System.out.println("getTime() = " + _who.getTime());
385 // 当前系统进程表中的用户名
386 System.out.println("getUser() = " + _who.getUser());
387 }
388 }
389
390
391 } catch (SigarException e) {
392 e.printStackTrace();
393 }
394 }
395 // 4.资源信息(主要是硬盘)
396 // a)取硬盘已有的分区及其详细信息(通过sigar.getFileSystemList()来获得FileSystem列表对象,然后对其进行编历):
397 public void testFileSystemInfo() throws Exception {
398 Sigar sigar = new Sigar();
399 FileSystem fslist[] = sigar.getFileSystemList();
400 //String dir = System.getProperty("user.home");// 当前用户文件夹路径
401 for (int i = 0; i < fslist.length; i++) {
402 System.out.println("/n~~~~~~~~~~" + i + "~~~~~~~~~~");
403 FileSystem fs = fslist;
404 // 分区的盘符名称
405 System.out.println("fs.getDevName() = " + fs.getDevName());
406 // 分区的盘符名称
407 System.out.println("fs.getDirName() = " + fs.getDirName());
408 System.out.println("fs.getFlags() = " + fs.getFlags());
409 // 文件系统类型,比如 FAT32NTFS
410 System.out.println("fs.getSysTypeName() = " + fs.getSysTypeName());
411 // 文件系统类型名,比如本地硬盘、光驱、网络文件系统等
412 System.out.println("fs.getTypeName() = " + fs.getTypeName());
413 // 文件系统类型
414 System.out.println("fs.getType() = " + fs.getType());
415 FileSystemUsage usage = null;
416 try {
417 usage = sigar.getFileSystemUsage(fs.getDirName());
418 } catch (SigarException e) {
419 if (fs.getType() == 2)
420 throw e;
421 continue;
422 }
423 switch (fs.getType()) {
424 case 0: // TYPE_UNKNOWN :未知
425 break;
426 case 1: // TYPE_NONE
427 break;
428 case 2: // TYPE_LOCAL_DISK : 本地硬盘
429 // 文件系统总大小
430 System.out.println(" Total = " + usage.getTotal() + "KB");
431
432
433 // 文件系统剩余大小
434 System.out.println(" Free = " + usage.getFree() + "KB");
435 // 文件系统可用大小
436 System.out.println(" Avail = " + usage.getAvail() + "KB");
437 // 文件系统已经使用量
438 System.out.println(" Used = " + usage.getUsed() + "KB");
439 double usePercent = usage.getUsePercent() * 100D;
440 // 文件系统资源的利用率
441 System.out.println(" Usage = " + usePercent + "%");
442 break;
443 case 3:// TYPE_NETWORK :网络
444 break;
445 case 4:// TYPE_RAM_DISK :闪存
446 break;
447 case 5:// TYPE_CDROM :光驱
448 break;
449 case 6:// TYPE_SWAP :页面交换
450 break;
451 }
452 System.out.println(" DiskReads = " + usage.getDiskReads());
453 System.out.println(" DiskWrites = " + usage.getDiskWrites());
454 }
455 return;
456 }
457 // 5.网络信息
458 // a)当前机器的正式域名
459 public String getFQDN() {
460 Sigar sigar = null;
461 try {
462 return InetAddress.getLocalHost().getCanonicalHostName();
463
464
465 } catch (UnknownHostException e) {
466 try {
467 sigar = new Sigar();
468 return sigar.getFQDN();
469 } catch (SigarException ex) {
470 return null;
471 } finally {
472 sigar.close();
473 }
474 }
475 }
476 // b)取到当前机器的IP地址
477
478
479 public String getDefaultIpAddress() {
480 String address = null;
481 try {
482
483
484 address = InetAddress.getLocalHost().getHostAddress();
485 // 没有出现异常而正常当取到的IP时,如果取到的不是网卡循回地址时就返回
486
487 // 否则再通过Sigar工具包中的方法来获取
488 if (!NetFlags.LOOPBACK_ADDRESS.equals(address)) {
489 return address;
490 }
491 } catch (UnknownHostException e) {
492
493
494 // hostname not in DNS or /etc/hosts
495 }
496 Sigar sigar = new Sigar();
497 try {
498
499
500 address = sigar.getNetInterfaceConfig().getAddress();
501
502
503 } catch (SigarException e) {
504
505
506 address = NetFlags.LOOPBACK_ADDRESS;
507
508
509 } finally {
510
511
512 sigar.close();
513
514
515 }
516
517
518 return address;
519
520
521 }
522 // c)取到当前机器的MAC地址
523
524
525 public String getMAC() {
526
527
528 Sigar sigar = null;
529
530
531 try {
532
533
534 sigar = new Sigar();
535
536
537 String[] ifaces = sigar.getNetInterfaceList();
538
539
540 String hwaddr = null;
541
542
543 for (int i = 0; i < ifaces.length; i++) {
544
545
546 NetInterfaceConfig cfg = sigar.getNetInterfaceConfig(ifaces);
547
548
549 if (NetFlags.LOOPBACK_ADDRESS.equals(cfg.getAddress())
550
551
552 || (cfg.getFlags() & NetFlags.IFF_LOOPBACK) != 0
553
554
555 || NetFlags.NULL_HWADDR.equals(cfg.getHwaddr())) {
556 continue;
557 }
558 /*
559 * 如果存在多张网卡包括虚拟机的网卡,默认只取第一张网卡的MAC地址,如果要返回所有的网卡(包括物理的和虚拟的)则可以修改方法的返回类型为数组或Collection
560 * ,通过在for循环里取到的多个MAC地址。
561 */
562 hwaddr = cfg.getHwaddr();
563 break;
564 }
565 return hwaddr != null ? hwaddr : null;
566 } catch (Exception e) {
567 return null;
568 } finally {
569 if (sigar != null)
570 sigar.close();
571 }
572 }
573 // d)获取网络流量等信息
574 public void testNetIfList() throws Exception {
575 Sigar sigar = new Sigar();
576 String ifNames[] = sigar.getNetInterfaceList();
577 for (int i = 0; i < ifNames.length; i++) {
578 String name = ifNames;
579 NetInterfaceConfig ifconfig = sigar.getNetInterfaceConfig(name);
580 print("/nname = " + name);// 网络设备名
581 print("Address = " + ifconfig.getAddress());// IP地址
582 print("Netmask = " + ifconfig.getNetmask());// 子网掩码
583 if ((ifconfig.getFlags() & 1L) <= 0L) {
584 print("!IFF_UP...skipping getNetInterfaceStat");
585 continue;
586 }
587 try {
588 NetInterfaceStat ifstat = sigar.getNetInterfaceStat(name);
589 print("RxPackets = " + ifstat.getRxPackets());// 接收的总包裹数
590 print("TxPackets = " + ifstat.getTxPackets());// 发送的总包裹数
591 print("RxBytes = " + ifstat.getRxBytes());// 接收到的总字节数
592 print("TxBytes = " + ifstat.getTxBytes());// 发送的总字节数
593 print("RxErrors = " + ifstat.getRxErrors());// 接收到的错误包数
594 print("TxErrors = " + ifstat.getTxErrors());// 发送数据包时的错误数
595 print("RxDropped = " + ifstat.getRxDropped());// 接收时丢弃的包数
596 print("TxDropped = " + ifstat.getTxDropped());// 发送时丢弃的包数
597 } catch (SigarNotImplementedException e) {
598 } catch (SigarException e) {
599 print(e.getMessage());
600
601
602 }
603 }
604 }
605 void print(String msg) {
606
607
608 System.out.println(msg);
609
610
611 }
612 // e)一些其他的信息
613 public void getEthernetInfo() {
614 Sigar sigar = null;
615 try {
616 sigar = new Sigar();
617 String[] ifaces = sigar.getNetInterfaceList();
618 for (int i = 0; i < ifaces.length; i++) {
619 NetInterfaceConfig cfg = sigar.getNetInterfaceConfig(ifaces);
620 if (NetFlags.LOOPBACK_ADDRESS.equals(cfg.getAddress())
621 || (cfg.getFlags() & NetFlags.IFF_LOOPBACK) != 0
622 || NetFlags.NULL_HWADDR.equals(cfg.getHwaddr())) {
623 continue;
624 }
625 System.out.println("cfg.getAddress() = " + cfg.getAddress());// IP地址
626 System.out.println("cfg.getBroadcast() = " + cfg.getBroadcast());// 网关广播地址
627 System.out.println("cfg.getHwaddr() = " + cfg.getHwaddr());// 网卡MAC地址
628 System.out.println("cfg.getNetmask() = " + cfg.getNetmask());// 子网掩码
629 System.out.println("cfg.getDescription() = "
630 + cfg.getDescription());// 网卡描述信息
631 System.out.println("cfg.getType() = " + cfg.getType());//
632 System.out.println("cfg.getDestination() = "
633 + cfg.getDestination());
634 System.out.println("cfg.getFlags() = " + cfg.getFlags());//
635 System.out.println("cfg.getMetric() = " + cfg.getMetric());
636 System.out.println("cfg.getMtu() = " + cfg.getMtu());
637 System.out.println("cfg.getName() = " + cfg.getName());
638 System.out.println();
639 }
640 } catch (Exception e) {
641 System.out.println("Error while creating GUID" + e);
642 } finally {
643 if (sigar != null)
644 sigar.close();
645
646 }
647 }
648 }

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马