当前位置:   article > 正文

如何利用Java获取系统的信息(CPU、内存、各盘符使用情况)_java 获取系统盘信息

java 获取系统盘信息
  1. /***********************************************************************
  2. * Project: gpsAdapter
  3. * Note: Console Application
  4. **********************************************************************/
  5. /**
  6. *
  7. * @author HuangHaifeng 1.0
  8. * @date 2016-1-12
  9. * @copyright CCompass
  10. * 增加用于监控系统cpu,memory的工具类
  11. */
  12. package com.hhf.test;
  13. import java.io.File;
  14. import java.io.InputStreamReader;
  15. import java.io.LineNumberReader;
  16. import java.lang.management.ManagementFactory;
  17. import java.util.ArrayList;
  18. import java.util.List;
  19. import javax.management.MBeanServerConnection;
  20. import javax.management.remote.JMXConnector;
  21. import javax.management.remote.JMXConnectorFactory;
  22. import javax.management.remote.JMXServiceURL;
  23. import com.sun.management.OperatingSystemMXBean;
  24. public class WindowsInfoUtil {
  25. private static final int CPUTIME = 500;
  26. private static final int PERCENT = 100;
  27. private static final int FAULTLENGTH = 10;
  28. // 获取内存使用率
  29. public static String getMemery() {
  30. OperatingSystemMXBean osmxb = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class);
  31. long totalvirtualMemory = osmxb.getTotalSwapSpaceSize(); // 剩余的物理内存
  32. long freePhysicalMemorySize = osmxb.getFreePhysicalMemorySize();
  33. Double compare = (Double) (1 - freePhysicalMemorySize * 1.0 / totalvirtualMemory) * 100;
  34. String str = compare.intValue() + "%";
  35. return str;
  36. }
  37. // 获取文件系统使用率
  38. public static List<String> getDisk() {
  39. // 操作系统
  40. List<String> list = new ArrayList<String>();
  41. for (char c = 'A'; c <= 'Z'; c++) {
  42. String dirName = c + ":/";
  43. File win = new File(dirName);
  44. if (win.exists()) {
  45. long total = (long) win.getTotalSpace();
  46. long free = (long) win.getFreeSpace();
  47. Double compare = (Double) (1 - free * 1.0 / total) * 100;
  48. String str = c + ":盘已使用" + compare.intValue() + "%";
  49. list.add(str);
  50. }
  51. }
  52. return list;
  53. }
  54. // 获得cpu使用率
  55. public static String getCpuRatioForWindows() {
  56. try {
  57. String procCmd = System.getenv("windir")
  58. + "\\system32\\wbem\\wmic.exe process get Caption,CommandLine,KernelModeTime,ReadOperationCount,ThreadCount,UserModeTime,WriteOperationCount";
  59. // 取进程信息
  60. long[] c0 = readCpu(Runtime.getRuntime().exec(procCmd));
  61. Thread.sleep(CPUTIME);
  62. long[] c1 = readCpu(Runtime.getRuntime().exec(procCmd));
  63. if (c0 != null && c1 != null) {
  64. long idletime = c1[0] - c0[0];
  65. long busytime = c1[1] - c0[1];
  66. return Double.valueOf(PERCENT * (busytime) * 1.0 / (busytime + idletime)).intValue() + "%";
  67. } else {
  68. return 0 + "%";
  69. }
  70. } catch (Exception ex) {
  71. ex.printStackTrace();
  72. return 0 + "%";
  73. }
  74. }
  75. private static long[] readCpu(final Process proc) {
  76. long[] retn = new long[2];
  77. try {
  78. proc.getOutputStream().close();
  79. InputStreamReader ir = new InputStreamReader(proc.getInputStream());
  80. LineNumberReader input = new LineNumberReader(ir);
  81. String line = input.readLine();
  82. if (line == null || line.length() < FAULTLENGTH) {
  83. return null;
  84. }
  85. int capidx = line.indexOf("Caption");
  86. int cmdidx = line.indexOf("CommandLine");
  87. int rocidx = line.indexOf("ReadOperationCount");
  88. int umtidx = line.indexOf("UserModeTime");
  89. int kmtidx = line.indexOf("KernelModeTime");
  90. int wocidx = line.indexOf("WriteOperationCount");
  91. long idletime = 0;
  92. long kneltime = 0;
  93. long usertime = 0;
  94. while ((line = input.readLine()) != null) {
  95. if (line.length() < wocidx) {
  96. continue;
  97. }
  98. // 字段出现顺序:Caption,CommandLine,KernelModeTime,ReadOperationCount,
  99. //ThreadCount,UserModeTime,WriteOperation
  100. String caption = Bytes.substring(line, capidx, cmdidx - 1).trim();
  101. String cmd = Bytes.substring(line, cmdidx, kmtidx - 1).trim();
  102. if (cmd.indexOf("wmic.exe") >= 0) {
  103. continue;
  104. }
  105. String s1 = Bytes.substring(line, kmtidx, rocidx - 1).trim();
  106. String s2 = Bytes.substring(line, umtidx, wocidx - 1).trim();
  107. if (caption.equals("System Idle Process") || caption.equals("System")) {
  108. if (s1.length() > 0)
  109. idletime += Long.valueOf(s1).longValue();
  110. if (s2.length() > 0)
  111. idletime += Long.valueOf(s2).longValue();
  112. continue;
  113. }
  114. if (s1.length() > 0)
  115. kneltime += Long.valueOf(s1).longValue();
  116. if (s2.length() > 0)
  117. usertime += Long.valueOf(s2).longValue();
  118. }
  119. retn[0] = idletime;
  120. retn[1] = kneltime + usertime;
  121. return retn;
  122. } catch (Exception ex) {
  123. ex.printStackTrace();
  124. } finally {
  125. try {
  126. proc.getInputStream().close();
  127. } catch (Exception e) {
  128. e.printStackTrace();
  129. }
  130. }
  131. return null;
  132. }
  133. static class Bytes {
  134. public static String substring(String src, int start_idx, int end_idx) {
  135. byte[] b = src.getBytes();
  136. String tgt = "";
  137. for (int i = start_idx; i <= end_idx; i++) {
  138. tgt += (char) b[i];
  139. }
  140. return tgt;
  141. }
  142. }
  143. public static void main(String[] args) throws Exception {
  144. System.out.println("cpu占有率=" + WindowsInfoUtil.getCpuRatioForWindows());
  145. System.out.println("可使用内存=" + WindowsInfoUtil.getMemery());
  146. System.out.println("各盘占用情况:" + WindowsInfoUtil.getDisk());
  147. }
  148. }

这时就会出现com.sun.management.OperatingSystemMXBean这个类找不到!

        这里的工程需要用到rt.jar,当我们额外下载导入rt.jar就可以解决这个问题,但是对于jdk来说本身是具有jar包的,原因是eclipse将这些访问受限制的API设置成了错误,导致不能import。



声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/58878
推荐阅读
相关标签
  

闽ICP备14008679号