使用Java获取系统信息的常用代码整理总结

所属分类: 软件编程 / java 阅读数: 52
收藏 0 赞 0 分享

1.获取CPU和内存信息

import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.ArrayList;
import java.util.List;
import mytools.com.sun.management.OperatingSystemMXBean;
import mytools.java.io.File;
import mytools.java.lang.management.ManagementFactory;
/**
 * 获取windows系统信息(CPU,内存,文件系统)
 * @author libing
 *
 */
public class WindowsInfoUtil {
  private static final int CPUTIME = 500;
  private static final int PERCENT = 100;
  private static final int FAULTLENGTH = 10;
  public static void main(String[] args) {
  System.out.println(getCpuRatioForWindows());
  System.out.println(getMemery());
  System.out.println(getDisk());
 }
 //获取内存使用率
 public static String getMemery(){
 OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
 // 总的物理内存+虚拟内存
 long totalvirtualMemory = osmxb.getTotalSwapSpaceSize();
 // 剩余的物理内存
 long freePhysicalMemorySize = osmxb.getFreePhysicalMemorySize();
 Double compare=(Double)(1-freePhysicalMemorySize*1.0/totalvirtualMemory)*100;
 String str="内存已使用:"+compare.intValue()+"%";
 return str;
 }
 //获取文件系统使用率
 public static List<String> getDisk() {
 // 操作系统
 List<String> list=new ArrayList<String>();
 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;
 }
 //获得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;
 }
}

2.获取本机的IP地址:

private static String getIpAddress() throws UnknownHostException { 
    InetAddress address = InetAddress.getLocalHost(); 
 
    return address.getHostAddress(); 
  }

 
3.获得网卡地址

public static String getMACAddress(){ 
 
    String address = ""; 
 
    String os = System.getProperty("os.name"); 
    String osUser=System.getProperty("user.name"); 
    if (os != null && os.startsWith("Windows")) { 
 
      try { 
 
        String command = "cmd.exe /c ipconfig /all"; 
         
        Process p = Runtime.getRuntime().exec(command); 
 
        BufferedReader br =new BufferedReader(new InputStreamReader(p.getInputStream())); 
 
        String line; 
 
        while ((line = br.readLine()) != null) { 
 
          if (line.indexOf("Physical Address") > 0) { 
 
            int index = line.indexOf(":"); 
 
            index += 2; 
 
            address = line.substring(index); 
 
            break; 
 
          } 
 
        } 
 
        br.close(); 
 
        return address.trim(); 
 
      } 
 
      catch (IOException e) { 
      } 
 
    } 
    return address; 
 
  } 

4.获得操作系统帐号

String osUser=System.getProperty("user.name"); 

5.获得操作系统版本

import java.util.Properties;  
   
Properties props=System.getProperties(); //获得系统属性集  
String osName = props.getProperty("os.name"); //操作系统名称  
String osArch = props.getProperty("os.arch"); //操作系统构架  
String osVersion = props.getProperty("os.version"); //操作系统版本

   
6.一些常用的信息获得方式整理

java.version    Java 运行时环境版本 
java.vendor     Java 运行时环境供应商 
java.vendor.url     Java 供应商的 URL 
java.home   Java 安装目录 
java.vm.specification.version   Java 虚拟机规范版本 
java.vm.specification.vendor    Java 虚拟机规范供应商 
java.vm.specification.name  Java 虚拟机规范名称 
java.vm.version     Java 虚拟机实现版本 
java.vm.vendor  Java 虚拟机实现供应商 
java.vm.name    Java 虚拟机实现名称 
java.specification.version  Java 运行时环境规范版本 
java.specification.vendor   Java 运行时环境规范供应商 
java.specification.name     Java 运行时环境规范名称 
java.class.version  Java 类格式版本号 
java.class.path     Java 类路径 
java.library.path   加载库时搜索的路径列表 
java.io.tmpdir  默认的临时文件路径 
java.compiler   要使用的 JIT 编译器的名称 
java.ext.dirs   一个或多个扩展目录的路径 
os.name     操作系统的名称 
os.arch     操作系统的架构 
os.version  操作系统的版本 
file.separator  文件分隔符(在 UNIX 系统中是“/”) 
path.separator  路径分隔符(在 UNIX 系统中是“:”) 
line.separator  行分隔符(在 UNIX 系统中是“/n”) 
user.name   用户的账户名称 
user.home   用户的主目录 
user.dir    用户的当前工作目录 

更多精彩内容其他人还在看

JavaWeb项目部署到服务器详细步骤详解

这篇文章主要介绍了JavaWeb项目如何部署到服务器,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
收藏 0 赞 0 分享

IDEA基于支付宝小程序搭建springboot项目的详细步骤

这篇文章主要介绍了IDEA基于支付宝小程序搭建springboot项目的详细步骤,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

详解SpringBoot应用服务启动与安全终止

这篇文章主要介绍了SpringBoot应用服务启动与安全终止,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
收藏 0 赞 0 分享

Spring Boot启动及退出加载项的方法

这篇文章主要介绍了Spring Boot启动及退出加载项的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
收藏 0 赞 0 分享

Spring Data Jpa 自动生成表结构的方法示例

这篇文章主要介绍了Spring Data Jpa 自动生成表结构的方法示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
收藏 0 赞 0 分享

IDEA中osgi的开发应用指南详解

这篇文章主要介绍了IDEA中osgi的开发应用指南详解,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

详解用maven将dubbo工程打成jar包运行

这篇文章主要介绍了详解用maven将dubbo工程打成jar包运行,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
收藏 0 赞 0 分享

详解Java合并数组的两种实现方式

这篇文章主要介绍了Java合并数组的两种实现方式,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
收藏 0 赞 0 分享

使用Jenkins Pipeline自动化构建发布Java项目的方法

这篇文章主要介绍了使用Jenkins Pipeline自动化构建发布Java项目的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

使用Maven配置Spring的方法步骤

这篇文章主要介绍了使用Maven配置Spring的方法步骤,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享
查看更多