展开全部
java获取所有系统信息(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;
}
}
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;
}
}
2015-06-24 · 知道合伙人数码行家
关注
展开全部
安装了java虚拟机以后的目录下有一个Demo文件夹,里面有很多范例,其中就有读取CPU信息,楼主可以找一找。
满意请采纳,谢谢你的支持!!!(๑•̀ㅂ•́)و✧
满意请采纳,谢谢你的支持!!!(๑•̀ㅂ•́)و✧
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
亲.java的目录下有一个Demo文件夹,里面有很多范例,其中就有读取CPU信息,望采纳点赞谢谢
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
安装了java虚拟机以后的目录下有一个Demo文件夹,里面有很多范例,其中就有读取CPU信息,楼主可以找一找。
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
Motherboard serial number
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class MiscUtils {
private MiscUtils() { }
public static String getMotherboardSN() {
String result = "";
try {
File file = File.createTempFile("realhowto",".vbs");
file.deleteOnExit();
FileWriter fw = new java.io.FileWriter(file);
String vbs =
"Set objWMIService = GetObject(\"winmgmts:\\\\.\\root\\cimv2\")\n"
+ "Set colItems = objWMIService.ExecQuery _ \n"
+ " (\"Select * from Win32_BaseBoard\") \n"
+ "For Each objItem in colItems \n"
+ " Wscript.Echo objItem.SerialNumber \n"
+ " exit for ' do the first cpu only! \n"
+ "Next \n";
fw.write(vbs);
fw.close();
Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());
BufferedReader input =
new BufferedReader
(new InputStreamReader(p.getInputStream()));
String line;
while ((line = input.readLine()) != null) {
result += line;
}
input.close();
}
catch(Exception e){
e.printStackTrace();
}
return result.trim();
}
public static void main(String[] args){
String cpuId = MiscUtils.getMotherboardSN();
javax.swing.JOptionPane.showConfirmDialog((java.awt.Component)
null, cpuId, "Motherboard serial number",
javax.swing.JOptionPane.DEFAULT_OPTION);
}
}
你试一试看看这段代码能否满足你的要求
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class MiscUtils {
private MiscUtils() { }
public static String getMotherboardSN() {
String result = "";
try {
File file = File.createTempFile("realhowto",".vbs");
file.deleteOnExit();
FileWriter fw = new java.io.FileWriter(file);
String vbs =
"Set objWMIService = GetObject(\"winmgmts:\\\\.\\root\\cimv2\")\n"
+ "Set colItems = objWMIService.ExecQuery _ \n"
+ " (\"Select * from Win32_BaseBoard\") \n"
+ "For Each objItem in colItems \n"
+ " Wscript.Echo objItem.SerialNumber \n"
+ " exit for ' do the first cpu only! \n"
+ "Next \n";
fw.write(vbs);
fw.close();
Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());
BufferedReader input =
new BufferedReader
(new InputStreamReader(p.getInputStream()));
String line;
while ((line = input.readLine()) != null) {
result += line;
}
input.close();
}
catch(Exception e){
e.printStackTrace();
}
return result.trim();
}
public static void main(String[] args){
String cpuId = MiscUtils.getMotherboardSN();
javax.swing.JOptionPane.showConfirmDialog((java.awt.Component)
null, cpuId, "Motherboard serial number",
javax.swing.JOptionPane.DEFAULT_OPTION);
}
}
你试一试看看这段代码能否满足你的要求
参考资料: http://www.rgagnon.com/javadetails/java-0580.html
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询