java获取cpu,内存,磁盘等信息 String类型转换为long,int

7 篇文章 0 订阅
/** 
* 获取windows系统信息(CPU,内存,文件系统) 
* @author www.zuidaima.com 
* 
*/ 
public class CPU {
    private static final int CPUTIME = 500; 
    private static final int PERCENT = 100; 
    private static final int FAULTLENGTH = 10; 
    
    public static void main(String[] args) { 
    	
		String a = "123";
	    System.out.println(Long.valueOf(a).longValue());
	    System.out.println(Integer.valueOf(a).intValue());
	    int b = 333;	
	    System.out.println(String.valueOf(b));
	    
	    
	    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();
	  System.out.println("总  的  内 存"+(totalvirtualMemory/1024.0/1024.0/1024.0));
	  System.out.println("使用的内存"+((totalvirtualMemory-freePhysicalMemorySize)/1024.0/1024.0/1024.0));
	  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对汉字处理存在问题(把一个汉字视为一个字节),因此在 包含汉字的字符串时存在隐患,现调整如下: 
	   * @author www.zuidaima.com 
	   * @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; 
	  } 
} 

获取CPU内存磁盘状态等信息,可以使用Java的ManagementFactory类和OperatingSystemMXBean接口来获取系统信息。 以下是获取CPU内存磁盘状态信息的示例代码: ``` import java.lang.management.ManagementFactory; import java.lang.management.OperatingSystemMXBean; import java.net.InetAddress; public class SystemInfo { public static void main(String[] args) throws Exception { // 获取本机IP地址 InetAddress addr = InetAddress.getLocalHost(); String ip = addr.getHostAddress(); System.out.println("IP地址:" + ip); // 获取操作系统信息 OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean(); System.out.println("操作系统:" + osmxb.getName() + " " + osmxb.getVersion()); // 获取CPU信息 int processors = osmxb.getAvailableProcessors(); System.out.println("CPU核数:" + processors); // 获取内存信息 long totalMemorySize = osmxb.getTotalPhysicalMemorySize() / 1024 / 1024; long freeMemorySize = osmxb.getFreePhysicalMemorySize() / 1024 / 1024; long usedMemorySize = totalMemorySize - freeMemorySize; System.out.println("总内存:" + totalMemorySize + "MB"); System.out.println("已用内存:" + usedMemorySize + "MB"); System.out.println("空闲内存:" + freeMemorySize + "MB"); // 获取磁盘信息 long totalDiskSpace = new File("/").getTotalSpace() / 1024 / 1024; long freeDiskSpace = new File("/").getFreeSpace() / 1024 / 1024; long usedDiskSpace = totalDiskSpace - freeDiskSpace; System.out.println("总磁盘空间:" + totalDiskSpace + "MB"); System.out.println("已用磁盘空间:" + usedDiskSpace + "MB"); System.out.println("剩余磁盘空间:" + freeDiskSpace + "MB"); } } ``` 注意:需要添加以下依赖才能使用ManagementFactory类和OperatingSystemMXBean接口: ``` <dependency> <groupId>javax.management</groupId> <artifactId>javax.management-api</artifactId> <version>2.0.0</version> </dependency> ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值