竹石 http://blianchen.blog.163.com/
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.lang.management.ManagementFactory;
import java.util.Properties;
import com.sun.management.OperatingSystemMXBean;
/**
* @author blc
*
*/
public class OSInfo {
private static OperatingSystemMXBean osmb =(OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
private static Properties props=System.getProperties(); //获得系统属性集
private static Runtime rt = Runtime.getRuntime(); //运行时
private static final int PERCENT = 100;
private static final int FAULTLENGTH = 10;
private static long[] firstc;
/**
* 操作系统构架
* @return
*/
public static String getOSArch() {
return props.getProperty("os.arch"); //操作系统构架
}
/**
* 操作系统名称
* @return
*/
public static String getOSName() {
return props.getProperty("os.name"); //操作系统名称
}
/**
* 操作系统版本
* @return
*/
public static String getOSVersion() {
return props.getProperty("os.version"); //操作系统版本
}
/**
* cpu数
* @return
*/
public static int getProcessorNum() {
return rt.availableProcessors(); //cpu数
}
/**
* 获取系统物理内存大小(M)
* @return xxM
*/
public static int getTotalPhysicalMemorySize(){
return (int)osmb.getTotalPhysicalMemorySize() / 1024 / 1024;
}
/**
* 获取系统物理空闲内存(M)
* @return xxM
*/
public static int getFreePhysicalMemorySize(){
OperatingSystemMXBean osmb =(OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
return (int)osmb.getFreePhysicalMemorySize()/ 1024 / 1024;
}
public static int getJVMTotalMemorySize(){
return (int)Runtime.getRuntime().totalMemory()/1024 /1024;
}
public static int getJVMFreeMemorySize(){
return (int)Runtime.getRuntime().freeMemory() /1024 /1024;
}
/**
* cpu使用百分比
* @return
*/
public static int getCpuRatio() {
if (getOSName().toLowerCase().startsWith("win")) {
return getCpuRatioForWindows();
} else {
throw new IllegalStateException();
}
}
/**
* 物理内存使用百分比
* @return
*/
public static int getPhysicalMemoryRatio() {
int tm = getTotalPhysicalMemorySize();
int fm = getFreePhysicalMemorySize();
return (tm-fm) * 100 / tm;
}
/**
* 获得CPU使用率. 通过两次取得任务管理器中的“System Idle Process”的值来计算
*
* @return 返回cpu使用率
* @author amg
*/
private static int getCpuRatioForWindows() {
try {
String procCmd = System.getenv("windir")
+ "\\system32\\wbem\\wmic.exe process get Caption,CommandLine,"
+ "KernelModeTime,ReadOperationCount,ThreadCount,UserModeTime,WriteOperationCount";
// 取进程信息
long[] c1 = readCpu(Runtime.getRuntime().exec(procCmd));
//第一次调用始终为零
if (firstc == null) {
firstc = c1;
return 0;
}
//计算使用率
if (firstc != null && c1 != null) {
long idletime = c1[0] - firstc[0];
long busytime = c1[1] - firstc[1];
firstc = c1;
return (int) (PERCENT * (busytime) / (busytime + idletime));
} else {
return 0;
}
} catch (Exception ex) {
ex.printStackTrace();
return 0;
}
}
/**
* 读取CPU信息.
*
* @param proc
* @return
* @author amg
*/
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 = Bytes.substring(line, capidx, cmdidx - 1)
.trim();
String cmd = Bytes.substring(line, cmdidx, kmtidx - 1).trim();
if (cmd.indexOf("wmic.exe") >= 0) {
continue;
}
// log.info("line="+line);
if (caption.equals("System Idle Process")
|| caption.equals("System")) {
idletime += Long.valueOf(
Bytes.substring(line, kmtidx, rocidx - 1).trim())
.longValue();
idletime += Long.valueOf(
Bytes.substring(line, umtidx, wocidx - 1).trim())
.longValue();
continue;
}
kneltime += Long.valueOf(
Bytes.substring(line, kmtidx, rocidx - 1).trim())
.longValue();
usertime += Long.valueOf(
Bytes.substring(line, umtidx, wocidx - 1).trim())
.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;
}
// public static float getFreeSwapSpaceSize(){
// return (float)osmb.getFreeSwapSpaceSize()/1024 /1024;
// }
//
// public static float getTotalSwapSpaceSize(){
// return (float)osmb.getTotalSwapSpaceSize()/1024 /1024;
// }
}
/**
* byte操作类.
* @author amg
*/
public class Bytes {
/**
* 由于String.subString对汉字处理存在问题(把一个汉字视为一个字节),因此在
* 包含汉字的字符串时存在隐患,现调整如下:
* @param src 要截取的字符串
* @param start_idx 开始坐标(包括该坐标)
* @param end_idx 截止坐标(包括该坐标)
* @return
*/
public 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;
}
}
其中的com.sun.management.OperatingSystemMXBean类是一个未公开的类,在myEclipse中编译时需要将下图的
Forbidden reference (access rules)选项改为警告或忽略。
评论