Java怎么获取windows系统信息,如CPU,内存,文件系统,硬盘大小? java实现这些功能的确有点麻烦,没有C语言方便.java在windows这方还是弱了一点.不过麻烦是麻烦点,针对这些功能还是可以实现了,以下是 自己整理的一些公用方法.与大家分享下.

private static final int CPUTIME = 500;
 private static final int PERCENT = 100;
 private static final int FAULTLENGTH = 10;

// // 获取内存使用率,这个方法有点问题,不没有解决
 // public static String getMemery(){
 // // OperatingSystemMXBean osmxb = (OperatingSystemMXBean)
 // ManagementFactory.getOperatingSystemMXBean();
 // OperatingSystemMXBean osmxb = (OperatingSystemMXBean)
 // ManagementFactory.getMemoryManagerMXBeans();
 // // 总的物理内存+虚拟内存
 // long totalvirtualMemory = osmxb.getTotalSwapSpaceSize();
 // osmxb.
 // 
 // // 剩余的物理内存
 // long freePhysicalMemorySize = osmxb.getFreePhysicalMemorySize();
 // Double
 // compare=(Double)(1-freePhysicalMemorySize*1.0/totalvirtualMemory)*100;
 // String str="内存已使用:"+compare.intValue()+"%";
 // return str;
 // }

// 获取文件系统使用率
 public static List getDisk() {
  // 操作系统
  List list = new ArrayList();
  for (char c = 'A'; c <= 'Z'; c++) {
   String dirName = c + ":/";
   File win = new File(dirName);
   if (win.exists()) {
    long total = (long) win.getTotalSpace();
    long free = (long) win.getFreeSpace();
    Double compare = (Double) (1 - free * 1.0 / total) * 100;
    String str = c + ":盘  已使用 " + compare.intValue() + "%";
    list.add(str);
   }
  }
  return list;
 }

// 单位为G
 public static List getDiskToG() {
  // 操作系统
  List list = new ArrayList();
  for (char c = 'A'; c <= 'Z'; c++) {
   String dirName = c + ":/";
   File win = new File(dirName);
   if (win.exists()) {
    long total = (long) win.getTotalSpace();
    long free = (long) win.getFreeSpace();
    DecimalFormat df2 = new DecimalFormat("###0.#"); //这个方法是对数字进行转换了,大家可以研究下
    double f1 = (free / (1024.0 * 1024 * 1024)); //free的值是字符类型,所以除以1024(1024字节等于1M)
    String str = c + "盘 可用空间" + df2.format(f1) + "G";
    list.add(str);
   }
  }
  return list;
 }

// 获得cpu使用率
 public static String getCpuRatioForWindows() {
  try {
   String procCmd = System.getenv("windir")
     + "
\\system32\\wbem\\wmic.exe process get Caption,CommandLine,KernelModeTime,ReadOperationCount,

ThreadCount,UserModeTime,WriteOperationCount";
   // 取进程信息
   long[] c0 = readCpu(Runtime.getRuntime().exec(procCmd));
   Thread.sleep(CPUTIME);
   long[] c1 = readCpu(Runtime.getRuntime().exec(procCmd));
   if (c0 != null && c1 != null) {
    long idletime = c1[0] - c0[0];
    long busytime = c1[1] - c0[1];
    return "CPU使用率:"
      + Double.valueOf(
        PERCENT * (busytime) * 1.0
          / (busytime + idletime)).intValue()
      + "%";
   } else {
    return "CPU使用率:" + 0 + "%";
   }
  } catch (Exception ex) {
   ex.printStackTrace();
   return "CPU使用率:" + 0 + "%";
  }
 }

// 读取cpu相关信息
 private static long[] readCpu(final Process proc) {
  long[] retn = new long[2];
  try {
   proc.getOutputStream().close();
   InputStreamReader ir = new InputStreamReader(proc.getInputStream());
   LineNumberReader input = new LineNumberReader(ir);
   String line = input.readLine();
   if (line == null || line.length() < FAULTLENGTH) {
    return null;
   }
   int capidx = line.indexOf("Caption");
   int cmdidx = line.indexOf("CommandLine");
   int rocidx = line.indexOf("ReadOperationCount");
   int umtidx = line.indexOf("UserModeTime");
   int kmtidx = line.indexOf("KernelModeTime");
   int wocidx = line.indexOf("WriteOperationCount");
   long idletime = 0;
   long kneltime = 0;
   long usertime = 0;
   while ((line = input.readLine()) != null) {
    if (line.length() < 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 (cmd.indexOf("wmic.exe") >= 0) {
     continue;
    }
    String s1 = substring(line, kmtidx, rocidx - 1).trim();
    String s2 = substring(line, umtidx, wocidx - 1).trim();
    if (caption.equals("System Idle Process")
      || caption.equals("System")) {
     if (s1.length() > 0)
      idletime += Long.valueOf(s1).longValue();
     if (s2.length() > 0)
      idletime += Long.valueOf(s2).longValue();
     continue;
    }
    if (s1.length() > 0)
     kneltime += Long.valueOf(s1).longValue();
    if (s2.length() > 0)
     usertime += Long.valueOf(s2).longValue();
   }
   retn[0] = idletime;
   retn[1] = kneltime + usertime;
   return retn;
  } catch (Exception ex) {
   ex.printStackTrace();
  } finally {
   try {
    proc.getInputStream().close();
   } catch (Exception e) {
    e.printStackTrace();
   }
  }
  return null;
 }

/**
  * 由于String.subString对汉字处理存在问题(把一个汉字视为一个字节),因此在 包含汉字的字符串时存在隐患,现调整如下:
  *
  * @param src
  *            要截取的字符串
  * @param start_idx
  *            开始坐标(包括该坐标)
  * @param end_idx
  *            截止坐标(包括该坐标)
  * @return
  */
 private static String substring(String src, int start_idx, int end_idx) {
  byte[] b = src.getBytes();
  String tgt = "";
  for (int i = start_idx; i <= end_idx; i++) {
   tgt += (char) b[i];
  }
  return tgt;
 }

测试下:

public static void main(String[] args) {
  System.out.println(getCpuRatioForWindows());
  // System.out.println(getMemery());
  System.out.println(getDisk());
  System.out.println(getDiskToG());

}

java获取windows系统信息(CPU,内存,文件系统,硬盘大小)相关推荐

  1. Unity3D 获取资源运行时内存和硬盘大小

    Unity3D

  2. 如何获取服务器的CPU,内存进行限流

    文章目录 如何获取服务器的CPU,内存进行限流 如何获取服务器的CPU,内存进行限流 需要包名 "github.com/shirou/gopsutil/v3/cpu""g ...

  3. JAVA获取图片的宽、高和大小

    JAVA获取图片的宽.高.大小 如果是本地磁盘文件 File file = new File("C:\\Users\\root\\Desktop\\test.jpg");Buffe ...

  4. java获取客户端系统信息_java 获得系统信息

    Java代码 import java.util.Properties; Properties props=System.getProperties(); //获得系统属性集 String osName ...

  5. C#-获取磁盘,cpu,内存信息

    获取磁盘信息zongdaxiao = GetHardDiskSpace("C") * 1.0 / 1024; user = GetHardDiskFreeSpace("C ...

  6. Java获取linux服务器cpu、内存、硬盘相关信息

    需要用到jcraft依赖,如果依赖失效,请前往官方获取jcraft官网,maven地址https://search.maven.org/artifact/com.jcraft/jsch <dep ...

  7. JAVA获取当前进程的内存占用数和CPU利用率以及读写字节数并计算统计信息

    通过oshi这个三方库来获取,目前这个最准确. 引入依赖 <dependency><groupId>com.github.oshi</groupId><art ...

  8. Java获取Aix系统cpu和内存使用率

    背景 需要增加熔断功能,但是之前写的是linux系统,在Aix系统中失效了,需要重新写. 原来的linux用的是/proc/meminfo./proc/stat这两个文件进行监控的,但是Aix中没有这 ...

  9. java获取服务器的cpu和内存使用率

    使用的是sigar.jar包 sigar.jar下载地址密码1j2r 使用方法这三个文件放到jdk安装目录的bin下: Sigar sigar = new Sigar();Mem mem = siga ...

最新文章

  1. MySQL优化篇:索引
  2. R语言观察日志(part11)--好用的R命令之高效安装
  3. Java Set接口详细讲解 TreeSet的定制排序和自然排序
  4. Selenium2+python自动化75-非input文件上传(SendKeys)
  5. Aruba7010 默认密码_钟祥人注意!手机这个密码必须设,否则危险!
  6. MSN登录问题:Error 80072ee7
  7. 【数字IC精品文章收录】近500篇文章|学习路线|基础知识|接口|总线|脚本语言|芯片求职|安全|EDA|工具|低功耗设计|Verilog|低功耗|STA|设计|验证|FPGA|架构|AMBA|书籍|
  8. 40个国内外文献免费下载网站-转
  9. java isprime函数_判断质数(isPrime)的方法——Java代码实现
  10. 戴尔笔记本电脑插入有线耳机后仍然外放的一种解决办法
  11. IDEA导入已有项目
  12. @SuppressWarnings注解用法详解
  13. 第四章 资本主义制度的形成及其本质
  14. UEStudio09.20.0.1007 注册码
  15. 微信公众平台的运营管理
  16. bilinear 神经网络_基于多尺度双线性卷积神经网络的多角度下车型精细识别
  17. Python编程-从入门到实践第15章课后习题详解
  18. Html5结合flash在所有主流播放器播放视频的方法
  19. pandas中计算分位数的方法describe,quantile,以及sql中计算分位数的方法percentile_approx,percent_rank() over()
  20. 计算机软考有哪些科目??

热门文章

  1. 多标签资源管理器哪个最好用
  2. 【Minecraft】【ModPC】【我的世界】 我的世界电脑版如何进入网络游戏?
  3. 最全Java成神学习路线总结!!!
  4. 将照片转换成漫画风格的API推荐
  5. Symbian 介绍
  6. ORM Bee学习捷径
  7. PyCharm 2016.1.3激活码
  8. 20天自刷/销量200笔不降权,真实交易只有26笔
  9. 全国计算机一级office2016版,全国一级计算机基础及MS-Office应用课件2016版.ppt
  10. Visual Studio 2005 简体中文版SP1了