java擷取cpu使用率/記憶體使用量率/硬碟的使用率

來源:互聯網
上載者:User

import java.io.File;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.lang.management.ManagementFactory;
import java.util.ArrayList;
import java.util.List;

import com.sun.management.OperatingSystemMXBean;

/**
 * 擷取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;
 }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.