本文目錄一覽:
- 1、使用java如何獲取遠程主機(引擎)的cpu性能,佔用內存,硬碟等信息(需要返回數據到前台頁面)
- 2、在Java中如何獲得當前系統的進程信息
- 3、如何用javavisualvm 來進行性能分析
- 4、java中如何獲得計算機的信息。
- 5、請問Java如何動態顯示當前內存佔用率餅圖
- 6、如何獲取java程序當前的使用內存
使用java如何獲取遠程主機(引擎)的cpu性能,佔用內存,硬碟等信息(需要返回數據到前台頁面)
我也這在做這方面的信息,我要寫一個java客戶端,發送命令調用遠程snmp,獲得一些相關信息
在Java中如何獲得當前系統的進程信息
1、在Windows的命令行 tasklist 可以獲得進程列表
你先CMD, 再執行tasklist 可以看到類似任務管理器里的進程信息
2、JAVA要調用CMD命令, 用 Process process = Runtime.getRuntime().exec(command);
例如:查找某進程
Process proc = Runtime.getRuntime().exec(“tasklist /FI \”IMAGENAME eq ” + processName + “\””);
bufferedReader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = null;
while ((line = bufferedReader.readLine()) != null) {
if (line.contains(“QQ.exe”)) {
System.out.printlns(“找到了”);
}
}
如何用javavisualvm 來進行性能分析
啟動jvisualvm
首先到JDK安裝目錄/bin目錄下,雙擊jvisualvm.exe文件啟動
進入jvisualvm界面,右側為正在運行的Java程序,打開了一個jconsole程序來做示例
雙擊要監控的Java進行,有關監控進程的概要,監控,線程等信息都會以圖像的方式顯現出來,能更方便的對Java運行程序做分析
右鍵左邊欄,正在運行的Java程序,可以執行Dump,線程,Dump堆的操作並且可以將正在運行的程序進行快照儲備,同時可以設置在發生內存溢出時自動生成Dump文件。
右鍵【文件】–【添加遠程主機】可對遠程運行的Java程序進行監控
菜單欄,工具–插件 輔助功能 可以幫助我們更細緻對Java程序進行監視分析,比如Visual GC 能顯示年輕代里的Eden區和survivor區的實時數據
Visualvm是一個非常實用的Java 監控工具,操作十分方便,多用幾次就會很快的入手啦。
java中如何獲得計算機的信息。
System.getProperties()
返回的是Properties
Properties 類表示了一個持久的屬性集
以下的代碼就可以把Properties的內容讀出來
Properties props = new Properties();
try {
InputStream in = new BufferedInputStream (new FileInputStream(filePath));
props.load(in);
Enumeration en = props.propertyNames();
while (en.hasMoreElements()) {
String key = (String) en.nextElement();
String Property = props.getProperty (key);
System.out.println(key+Property);
}
} catch (Exception e) {
e.printStackTrace();
}
對於補充的回答:
java不能直接得到樓主需要的信息,但是可以採用JNI,即調用C程序,讓C得到這些信息
請問Java如何動態顯示當前內存佔用率餅圖
這個東西不好找,想要你的分,找了一下午呢,下面的程序能讀到內存使用情況,把讀到的數據放在棧里,GUI的圖餅類每隔0.5秒取棧里拿一次數據,然後刷新圖餅就行了
JXM:Monitoring and Management Interface for the Java™ Platform
通過jmx可以監控vm內存使用,系統內存使用等
以下是網上某博客代碼,特點是通過window和linux命令獲得CPU使用率。
Java代碼
利用java程序實現獲取計算機cpu利用率和內存使用信息。
創建一個Bean用來存貯要得到的信
public class MonitorInfoBean {
/** 可使用內存. */
private long totalMemory;
/** 剩餘內存. */
private long freeMemory;
/** 最大可使用內存. */
private long maxMemory;
/** 操作系統. */
private String osName;
/** 總的物理內存. */
private long totalMemorySize;
/** 剩餘的物理內存. */
private long freePhysicalMemorySize;
/** 已使用的物理內存. */
private long usedMemory;
/** 線程總數. */
private int totalThread;
/** cpu使用率. */
private double cpuRatio;
public long getFreeMemory() {
return freeMemory;
}
public void setFreeMemory(long freeMemory) {
this.freeMemory = freeMemory;
}
public long getFreePhysicalMemorySize() {
return freePhysicalMemorySize;
}
public void setFreePhysicalMemorySize(long freePhysicalMemorySize) {
this.freePhysicalMemorySize = freePhysicalMemorySize;
}
public long getMaxMemory() {
return maxMemory;
}
public void setMaxMemory(long maxMemory) {
this.maxMemory = maxMemory;
}
public String getOsName() {
return osName;
}
public void setOsName(String osName) {
this.osName = osName;
}
public long getTotalMemory() {
return totalMemory;
}
public void setTotalMemory(long totalMemory) {
this.totalMemory = totalMemory;
}
public long getTotalMemorySize() {
return totalMemorySize;
}
public void setTotalMemorySize(long totalMemorySize) {
this.totalMemorySize = totalMemorySize;
}
public int getTotalThread() {
return totalThread;
}
public void setTotalThread(int totalThread) {
this.totalThread = totalThread;
}
public long getUsedMemory() {
return usedMemory;
}
public void setUsedMemory(long usedMemory) {
this.usedMemory = usedMemory;
}
public double getCpuRatio() {
return cpuRatio;
}
public void setCpuRatio(double cpuRatio) {
this.cpuRatio = cpuRatio;
}
}
之後,建立bean的介面
public interface IMonitorService {
public MonitorInfoBean getMonitorInfoBean() throws Exception;
}
然後,就是最關鍵的,得到cpu的利用率,已用內存,可用內存,最大內存等信息。
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import sun.management.ManagementFactory;
import com.sun.management.OperatingSystemMXBean;
import java.io.*;
import java.util.StringTokenizer;
/**
* 獲取系統信息的業務邏輯實現類.
* @author GuoHuang
*/
public class MonitorServiceImpl implements IMonitorService {
private static final int CPUTIME = 30;
private static final int PERCENT = 100;
private static final int FAULTLENGTH = 10;
private static final File versionFile = new File(“/proc/version”);
private static String linuxVersion = null;
/**
* 獲得當前的監控對象.
* @return 返回構造好的監控對象
* @throws Exception
* @author GuoHuang
*/
public MonitorInfoBean getMonitorInfoBean() throws Exception {
int kb = 1024;
// 可使用內存
long totalMemory = Runtime.getRuntime().totalMemory() / kb;
// 剩餘內存
long freeMemory = Runtime.getRuntime().freeMemory() / kb;
// 最大可使用內存
long maxMemory = Runtime.getRuntime().maxMemory() / kb;
OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory
.getOperatingSystemMXBean();
// 操作系統
String osName = System.getProperty(“os.name”);
// 總的物理內存
long totalMemorySize = osmxb.getTotalPhysicalMemorySize() / kb;
// 剩餘的物理內存
long freePhysicalMemorySize = osmxb.getFreePhysicalMemorySize() / kb;
// 已使用的物理內存
long usedMemory = (osmxb.getTotalPhysicalMemorySize() – osmxb
.getFreePhysicalMemorySize())
/ kb;
// 獲得線程總數
ThreadGroup parentThread;
for (parentThread = Thread.currentThread().getThreadGroup(); parentThread
.getParent() != null; parentThread = parentThread.getParent())
;
int totalThread = parentThread.activeCount();
double cpuRatio = 0;
if (osName.toLowerCase().startsWith(“windows”)) {
cpuRatio = this.getCpuRatioForWindows();
}
else {
cpuRatio = this.getCpuRateForLinux();
}
// 構造返回對象
MonitorInfoBean infoBean = new MonitorInfoBean();
infoBean.setFreeMemory(freeMemory);
infoBean.setFreePhysicalMemorySize(freePhysicalMemorySize);
infoBean.setMaxMemory(maxMemory);
infoBean.setOsName(osName);
infoBean.setTotalMemory(totalMemory);
infoBean.setTotalMemorySize(totalMemorySize);
infoBean.setTotalThread(totalThread);
infoBean.setUsedMemory(usedMemory);
infoBean.setCpuRatio(cpuRatio);
return infoBean;
}
private static double getCpuRateForLinux(){
InputStream is = null;
InputStreamReader isr = null;
BufferedReader brStat = null;
StringTokenizer tokenStat = null;
try{
System.out.println(“Get usage rate of CUP , linux version: “+linuxVersion);
Process process = Runtime.getRuntime().exec(“top -b -n 1”);
is = process.getInputStream();
isr = new InputStreamReader(is);
brStat = new BufferedReader(isr);
if(linuxVersion.equals(“2.4”)){
brStat.readLine();
brStat.readLine();
brStat.readLine();
brStat.readLine();
tokenStat = new StringTokenizer(brStat.readLine());
tokenStat.nextToken();
tokenStat.nextToken();
String user = tokenStat.nextToken();
tokenStat.nextToken();
String system = tokenStat.nextToken();
tokenStat.nextToken();
String nice = tokenStat.nextToken();
System.out.println(user+” , “+system+” , “+nice);
user = user.substring(0,user.indexOf(“%”));
system = system.substring(0,system.indexOf(“%”));
nice = nice.substring(0,nice.indexOf(“%”));
float userUsage = new Float(user).floatValue();
float systemUsage = new Float(system).floatValue();
float niceUsage = new Float(nice).floatValue();
return (userUsage+systemUsage+niceUsage)/100;
}else{
brStat.readLine();
brStat.readLine();
tokenStat = new StringTokenizer(brStat.readLine());
tokenStat.nextToken();
tokenStat.nextToken();
tokenStat.nextToken();
tokenStat.nextToken();
tokenStat.nextToken();
tokenStat.nextToken();
tokenStat.nextToken();
String cpuUsage = tokenStat.nextToken();
System.out.println(“CPU idle : “+cpuUsage);
Float usage = new Float(cpuUsage.substring(0,cpuUsage.indexOf(“%”)));
return (1-usage.floatValue()/100);
}
} catch(IOException ioe){
System.out.println(ioe.getMessage());
freeResource(is, isr, brStat);
return 1;
} finally{
freeResource(is, isr, brStat);
}
}
private static void freeResource(InputStream is, InputStreamReader isr, BufferedReader br){
try{
if(is!=null)
is.close();
if(isr!=null)
isr.close();
if(br!=null)
br.close();
}catch(IOException ioe){
System.out.println(ioe.getMessage());
}
}
/**
* 獲得CPU使用率.
* @return 返回cpu使用率
* @author GuoHuang
*/
private double 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 Double.valueOf(
PERCENT * (busytime) / (busytime + idletime))
.doubleValue();
} else {
return 0.0;
}
} catch (Exception ex) {
ex.printStackTrace();
return 0.0;
}
}
/**
* 讀取CPU信息.
* @param proc
* @return
* @author GuoHuang
*/
private 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;
}
/** 測試方法.
* @param args
* @throws Exception
* @author GuoHuang
*/
public static void main(String[] args) throws Exception {
IMonitorService service = new MonitorServiceImpl();
MonitorInfoBean monitorInfo = service.getMonitorInfoBean();
System.out.println(“cpu佔有率=” + monitorInfo.getCpuRatio());
System.out.println(“可使用內存=” + monitorInfo.getTotalMemory());
System.out.println(“剩餘內存=” + monitorInfo.getFreeMemory());
System.out.println(“最大可使用內存=” + monitorInfo.getMaxMemory());
System.out.println(“操作系統=” + monitorInfo.getOsName());
System.out.println(“總的物理內存=” + monitorInfo.getTotalMemorySize() + “kb”);
System.out.println(“剩餘的物理內存=” + monitorInfo.getFreeMemory() + “kb”);
System.out.println(“已使用的物理內存=” + monitorInfo.getUsedMemory() + “kb”);
System.out.println(“線程總數=” + monitorInfo.getTotalThread() + “kb”);
}
}
其中,Bytes類用來處理字元串
public class Bytes {
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;
}
}
如何獲取java程序當前的使用內存
方法如下:
首先
創建一個Bean用來存貯要得到的信
public class MonitorInfoBean {
/** 可使用內存. */
private long totalMemory;
/** 剩餘內存. */
private long freeMemory;
/** 最大可使用內存. */
private long maxMemory;
/** 操作系統. */
private String osName;
/** 總的物理內存. */
private long totalMemorySize;
/** 剩餘的物理內存. */
private long freePhysicalMemorySize;
/** 已使用的物理內存. */
private long usedMemory;
/** 線程總數. */
private int totalThread;
/** cpu使用率. */
private double cpuRatio;
public long getFreeMemory() {
return freeMemory;
}
public void setFreeMemory(long freeMemory) {
this.freeMemory = freeMemory;
}
public long getFreePhysicalMemorySize() {
return freePhysicalMemorySize;
}
public void setFreePhysicalMemorySize(long freePhysicalMemorySize) {
this.freePhysicalMemorySize = freePhysicalMemorySize;
}
public long getMaxMemory() {
return maxMemory;
}
public void setMaxMemory(long maxMemory) {
this.maxMemory = maxMemory;
}
public String getOsName() {
return osName;
}
public void setOsName(String osName) {
this.osName = osName;
}
public long getTotalMemory() {
return totalMemory;
}
public void setTotalMemory(long totalMemory) {
this.totalMemory = totalMemory;
}
public long getTotalMemorySize() {
return totalMemorySize;
}
public void setTotalMemorySize(long totalMemorySize) {
this.totalMemorySize = totalMemorySize;
}
public int getTotalThread() {
return totalThread;
}
public void setTotalThread(int totalThread) {
this.totalThread = totalThread;
}
public long getUsedMemory() {
return usedMemory;
}
public void setUsedMemory(long usedMemory) {
this.usedMemory = usedMemory;
}
public double getCpuRatio() {
return cpuRatio;
}
public void setCpuRatio(double cpuRatio) {
this.cpuRatio = cpuRatio;
}
}
之後,建立bean的介面
public interface IMonitorService {
public MonitorInfoBean getMonitorInfoBean() throws Exception;
}
然後,就是最關鍵的,得到cpu的利用率,已用內存,可用內存,最大內存等信息。
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import sun.management.ManagementFactory;
import com.sun.management.OperatingSystemMXBean;
import java.io.*;
import java.util.StringTokenizer;
/**
* 獲取系統信息的業務邏輯實現類.
* @author GuoHuang
*/
public class MonitorServiceImpl implements IMonitorService {
private static final int CPUTIME = 30;
private static final int PERCENT = 100;
private static final int FAULTLENGTH = 10;
private static final File versionFile = new File(“/proc/version”);
private static String linuxVersion = null;
/**
* 獲得當前的監控對象.
* @return 返回構造好的監控對象
* @throws Exception
* @author GuoHuang
*/
public MonitorInfoBean getMonitorInfoBean() throws Exception {
int kb = 1024;
// 可使用內存
long totalMemory = Runtime.getRuntime().totalMemory() / kb;
// 剩餘內存
long freeMemory = Runtime.getRuntime().freeMemory() / kb;
// 最大可使用內存
long maxMemory = Runtime.getRuntime().maxMemory() / kb;
OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory
.getOperatingSystemMXBean();
// 操作系統
String osName = System.getProperty(“os.name”);
// 總的物理內存
long totalMemorySize = osmxb.getTotalPhysicalMemorySize() / kb;
// 剩餘的物理內存
long freePhysicalMemorySize = osmxb.getFreePhysicalMemorySize() / kb;
// 已使用的物理內存
long usedMemory = (osmxb.getTotalPhysicalMemorySize() – osmxb
.getFreePhysicalMemorySize())
/ kb;
// 獲得線程總數
ThreadGroup parentThread;
for (parentThread = Thread.currentThread().getThreadGroup(); parentThread
.getParent() != null; parentThread = parentThread.getParent())
;
int totalThread = parentThread.activeCount();
double cpuRatio = 0;
if (osName.toLowerCase().startsWith(“windows”)) {
cpuRatio = this.getCpuRatioForWindows();
}
else {
cpuRatio = this.getCpuRateForLinux();
}
// 構造返回對象
MonitorInfoBean infoBean = new MonitorInfoBean();
infoBean.setFreeMemory(freeMemory);
infoBean.setFreePhysicalMemorySize(freePhysicalMemorySize);
infoBean.setMaxMemory(maxMemory);
infoBean.setOsName(osName);
infoBean.setTotalMemory(totalMemory);
infoBean.setTotalMemorySize(totalMemorySize);
infoBean.setTotalThread(totalThread);
infoBean.setUsedMemory(usedMemory);
infoBean.setCpuRatio(cpuRatio);
return infoBean;
}
private static double getCpuRateForLinux(){
InputStream is = null;
InputStreamReader isr = null;
BufferedReader brStat = null;
StringTokenizer tokenStat = null;
try{
System.out.println(“Get usage rate of CUP , linux version: “+linuxVersion);
Process process = Runtime.getRuntime().exec(“top -b -n 1”);
is = process.getInputStream();
isr = new InputStreamReader(is);
brStat = new BufferedReader(isr);
if(linuxVersion.equals(“2.4”)){
brStat.readLine();
brStat.readLine();
brStat.readLine();
brStat.readLine();
tokenStat = new StringTokenizer(brStat.readLine());
tokenStat.nextToken();
tokenStat.nextToken();
String user = tokenStat.nextToken();
tokenStat.nextToken();
String system = tokenStat.nextToken();
tokenStat.nextToken();
String nice = tokenStat.nextToken();
System.out.println(user+” , “+system+” , “+nice);
user = user.substring(0,user.indexOf(“%”));
system = system.substring(0,system.indexOf(“%”));
nice = nice.substring(0,nice.indexOf(“%”));
float userUsage = new Float(user).floatValue();
float systemUsage = new Float(system).floatValue();
float niceUsage = new Float(nice).floatValue();
return (userUsage+systemUsage+niceUsage)/100;
}else{
brStat.readLine();
brStat.readLine();
tokenStat = new StringTokenizer(brStat.readLine());
tokenStat.nextToken();
tokenStat.nextToken();
tokenStat.nextToken();
tokenStat.nextToken();
tokenStat.nextToken();
tokenStat.nextToken();
tokenStat.nextToken();
String cpuUsage = tokenStat.nextToken();
System.out.println(“CPU idle : “+cpuUsage);
Float usage = new Float(cpuUsage.substring(0,cpuUsage.indexOf(“%”)));
return (1-usage.floatValue()/100);
}
} catch(IOException ioe){
System.out.println(ioe.getMessage());
freeResource(is, isr, brStat);
return 1;
} finally{
freeResource(is, isr, brStat);
}
}
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/286447.html