java读取硬件信息

合集下载

java 读取ca证书内容

java 读取ca证书内容

java 读取ca证书内容如何使用Java读取CA证书的内容?CA证书在网络通信中扮演着重要的角色,用于验证服务器的身份并确保通信的安全性。

为了了解CA证书的内容,我们可以使用Java编程语言来读取并提取证书中的关键信息。

本文将一步一步地介绍如何使用Java读取CA证书的内容。

第一步:导入必要的类和包我们需要导入Java的一些类和包来执行证书的读取操作。

首先,我们需要导入`java.io`和`java.nio.file`包以处理文件读写操作。

其次,我们需要导入`java.security.cert`包以使用Java的Certificate类,以及`java.security.KeyStore`类来读取密钥库文件。

最后,我们需要导入`java.util`包以便使用Java的Map和Iterator类。

javaimport java.io.*;import java.nio.file.Files;import java.nio.file.Paths;import java.security.cert.Certificate;import java.security.KeyStore;import java.util.Map;import java.util.Iterator;第二步:加载CA证书文件CA证书通常以PEM(Privacy Enhanced Mail)或DER(Distinguished Encoding Rules)格式保存在文件中。

我们可以使用Java的文件操作方法加载证书文件。

下面是加载PEM格式证书文件的代码示例:javaFile pemFile = new File("path/to/ca.pem");byte[] pemBytes = Files.readAllBytes(pemFile.toPath());对于DER格式证书文件,我们可以使用类似的方法来加载文件:javaFile derFile = new File("path/to/ca.der");byte[] derBytes = Files.readAllBytes(derFile.toPath());第三步:创建Certificate对象在接下来的步骤中,我们将使用Java的Certificate类来操作CA证书的内容。

java程序读取服务器端数据文件的方法

java程序读取服务器端数据文件的方法

java程序读取服务器端数据文件的方法
1. 使用Java IO流读取服务器端文件:
使用Java IO流可以读取服务器端文件,具体步骤如下:
(1)使用URL类的openStream()方法获取URL对象的输入流;
(2)使用BufferedReader类的readLine()方法读取文件内容;
(3)使用String类的split()方法将读取的内容按照指定的分隔符分割为字符串数组;
(4)使用Arrays类的toString()方法将字符串数组转换为字符串;
(5)使用String类的replace()方法替换掉特殊字符;
(6)使用String类的split()方法将字符串按照指定的分隔符分割为字符串数组;
(7)使用for循环遍历字符串数组,将每个字符串元素添加到ArrayList中;
(8)将ArrayList转换为字符串数组,并返回。

2. 使用Java NIO读取服务器端文件:
使用Java NIO可以读取服务器端文件,具体步骤如下:
(1)使用Paths类的get()方法获取服务器端文件的路径;
(2)使用Files类的readAllBytes()方法读取文件的所有字节;
(3)使用String类的split()方法将读取的内容按照指定的分隔符分割为字符串数组;
(4)使用for循环遍历字符串数组,将每个字符串元素添加到ArrayList中;
(5)将ArrayList转换为字符串数组,并返回。

JAVA获得CPU和内存的使用情况的两种方法

JAVA获得CPU和内存的使用情况的两种方法

JAVA获得CPU和内存的使用情况的两种方法在Java中,可以使用不同的方法来获取CPU和内存的使用情况。

这些信息对于优化程序性能和资源管理非常重要。

以下是两种常用的方法:1. 使用Java Management Extensions(JMX):Java提供了JMX API来监控和管理Java应用程序。

通过使用JMX,可以获取有关系统资源的详细信息,包括CPU和内存使用情况。

a)获取CPU使用情况:要获取CPU使用情况,可以使用ng.management包中的ThreadMXBean接口。

ThreadMXBean接口提供了许多有用的方法,例如getThreadCpuTime(来获取线程的CPU时间。

可以使用以下代码来获取整个系统的CPU使用情况:```javaimport ng.management.ManagementFactory;import ng.management.ThreadMXBean;public class CPUMonitorpublic static void main(String[] args)ThreadMXBean threadMXBean =ManagementFactory.getThreadMXBean(;long cpuTime = threadMXBean.getCurrentThreadCpuTime(;System.out.println("CPU Time: " + cpuTime);}}```b)获取内存使用情况:要获取内存使用情况,可以使用ng.management包中的MemoryMXBean和MemoryUsage类。

MemoryMXBean提供了获取内存使用情况的方法,而MemoryUsage类用于表示内存使用情况。

以下是一个示例代码:```javaimport ng.management.ManagementFactory;import ng.management.MemoryMXBean;import ng.management.MemoryUsage;public class MemoryMonitorpublic static void main(String[] args)MemoryMXBean memoryMXBean =ManagementFactory.getMemoryMXBean(;MemoryUsage heapMemoryUsage =memoryMXBean.getHeapMemoryUsage(;MemoryUsage nonHeapMemoryUsage =memoryMXBean.getNonHeapMemoryUsage(;System.out.println("Heap Memory Usage: " + heapMemoryUsage);System.out.println("Non-Heap Memory Usage: " + nonHeapMemoryUsage);}}```2. 使用操作系统命令和Java进程的ManagementFactory:Java还提供了一种通过执行操作系统命令并解析结果来获取CPU和内存使用情况的方法。

java systeminfo详解

java systeminfo详解

java systeminfo详解Java SystemInfo是一个用于获取系统信息的Java库。

它提供了一些用于查询操作系统和硬件信息的方法,可以帮助开发人员更好地了解和管理系统。

这个库可以用于开发各种Java应用程序,比如系统监控工具、系统配置管理工具等。

Java SystemInfo提供了一系列静态方法来获取系统信息。

比如,可以使用`SystemInfo.getOperatingSystem()`方法获取操作系统的信息,包括名称、版本号、架构等。

可以使用`SystemInfo.getHardware()`方法获取硬件信息,包括处理器、内存、磁盘等。

可以使用`SystemInfo.getNetworkIFs()`方法获取网络接口的信息,包括名称、IP地址、MAC地址等。

还可以使用`SystemInfo.getFileSystem()`方法获取文件系统的信息,包括根目录、总空间、可用空间等。

Java SystemInfo还提供了一些辅助方法来处理系统信息。

比如,可以使用`SystemInfo.getUptime()`方法获取系统的运行时间,以毫秒为单位。

可以使用`SystemInfo.getJavaInfo()`方法获取当前Java运行时的信息,包括版本号、供应商等。

可以使用`SystemInfo.getJavaFXInfo()`方法获取当前JavaFX运行时的信息,比如版本号、供应商等。

除了获取系统信息,Java SystemInfo还提供了一些其他功能。

比如,可以使用`SystemInfo.getUserInfo()`方法获取当前用户的信息,包括用户名、用户主目录等。

可以使用`SystemInfo.getProcesses()`方法获取当前系统的进程列表,包括进程ID、进程名称等。

可以使用`SystemInfo.getSensors()`方法获取系统的传感器信息,比如温度、风扇速度等。

使用Java SystemInfo需要在项目中引入相关的依赖。

java 读取外部配置文件的方法

java 读取外部配置文件的方法

java 读取外部配置文件的方法Java是一种面向对象的编程语言,具有广泛的应用领域。

在Java开发中,有时需要读取外部配置文件来获取一些参数或配置信息。

下面将介绍一些常见的Java读取外部配置文件的方法。

1. 使用Java的Properties类:Java的Properties类是处理属性文件的工具类,非常适合读取外部配置文件。

以下是一个简单的示例代码:```javaimport java.io.FileInputStream;import java.io.IOException;import java.util.Properties;public class ReadConfigFile {public static void main(String[] args) {Properties prop = new Properties();try {prop.load(new FileInputStream("config.properties"));String value1 = prop.getProperty("key1");String value2 = prop.getProperty("key2");// 使用读取到的配置信息进行后续操作} catch (IOException e) {e.printStackTrace();}}}```通过创建Properties对象并使用load()方法来读取配置文件,可以通过getProperty()方法获取配置文件中的具体键值对。

2. 使用Java的ResourceBundle类:ResourceBundle类提供了一种读取以属性键值对形式存储的配置文件的方式。

以下是一个简单的示例代码:```javaimport java.util.ResourceBundle;public class ReadConfigFile {public static void main(String[] args) {ResourceBundle bundle = ResourceBundle.getBundle("config");String value1 = bundle.getString("key1");String value2 = bundle.getString("key2");// 使用读取到的配置信息进行后续操作}}```使用getBundle()方法加载配置文件,通过getString()方法获取具体的配置信息。

Java获取系统信息(cpu,内存,硬盘,进程等)的相关方法

Java获取系统信息(cpu,内存,硬盘,进程等)的相关方法

java获取系统信息(CPU,内存,硬盘,进程)的相关方法一、这是一个获取相关信息的简单的方法import java.io.*;import com.sun.management.OperatingSystemMXBean;import sun.management.ManagementFactory;public class Tst{public static String pt="D:\\abc.txt";public Tst(){}public static void main(String[] args) throws Exception{//free和use和total均为KBlong free=0;long use=0;long total=0;int kb=1024;Runtime rt=Runtime.getRuntime();total=rt.totalMemory();free=rt.freeMemory();use=total-free;System.out.println("系统内存已用的空间为:"+use/kb+" MB");System.out.println("系统内存的空闲空间为:"+free/kb+" MB");System.out.println("系统总内存空间为:"+total/kb+" MB");OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();long physicalFree=osmxb.getFreePhysicalMemorySize()/kb;long physicalTotal=osmxb.getTotalPhysicalMemorySize()/kb;long physicalUse=physicalTotal-physicalFree;String os=System.getProperty("");System.out.println("操作系统的版本:"+os);System.out.println("系统物理内存已用的空间为:"+physicalFree+" MB");System.out.println("系统物理内存的空闲空间为:"+physicalUse+" MB");System.out.println("总物理内存:"+physicalTotal+" MB");// 获得线程总数ThreadGroup parentThread;for (parentThread = Thread.currentThread().getThreadGroup(); parentThread.getParent() != null; parentThread = parentThread.getParent());int totalThread = parentThread.activeCount();System.out.println("获得线程总数:"+totalThread);}}二,别的方法技巧1.利用jdk自带的API获取信息:(只支持jdk1.60以上的版本啊)import java.io.InputStreamReader;import java.io.LineNumberReader;import java.util.ArrayList;import java.util.List;import .sun.management.OperatingSystemMXBean; import mytools.java.io.File;import ng.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.exeprocess getCaption,CommandLine,KernelModeTime,ReadOperationCount,ThreadCount,UserModeT ime,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) {}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,WriteOperationString 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();}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;}}2.利用第三方的jar包:(Hyperic-hq官方网站:)通过Hyperic-hq产品的基础包sigar.jar来实现服务器状态数据的获取。

java 获取指定服务器信息的方法

一、概述Java作为一种广泛使用的编程语言,具有强大的跨评台能力和丰富的库支持,因此在网络编程中也有着广泛的应用。

在实际开发中,我们经常需要获取指定服务器信息,比如IP位置区域、主机名、操作系统信息等。

本文将介绍在Java中获取指定服务器信息的方法,希望能对读者有所帮助。

二、获取IP位置区域1. 使用InetAddress类Java中的InetAddress类提供了获取主机的IP位置区域的方法,可以通过该类获取指定主机的IP位置区域。

示例代码如下:```javaimport .InetAddress;import .UnknownHostException;public class GetServerInfo {public static void m本人n(String[] args) {try {InetAddress address = InetAddress.getByName("xxx");address.getHostAddress());} catch (UnknownHostException e) {e.printStackTrace();}}}```2. 使用.*包除了InetAddress类之外,还可以使用.*包中的其他类来获取IP位置区域。

使用Socket类连接指定服务器并获取其IP位置区域:```javaimport java.io.*;import .*;public class GetServerInfo {public static void m本人n(String[] args) {try {Socket socket = new Socket("xxx", 80);InetAddress address = socket.getInetAddress();address.getHostAddress());socket.close();} catch (IOException e) {e.printStackTrace();}}}```三、获取主机名1. 使用InetAddress类除了获取IP位置区域,InetAddress类还可以用来获取主机名。

java获取cpu核数的方法

java获取cpu核数的方法Java中获取CPU核数的方法有多种,可以使用Java API或者操作系统命令等方式。

1. 使用Java API获取CPU核数:Java提供了Runtime类,可以使用该类的availableProcessors()方法获取当前系统环境下的CPU核数。

示例代码如下:int core = Runtime.getRuntime().availableProcessors();System.out.println('CPU核数:' + core);2. 使用操作系统命令获取CPU核数:可以使用操作系统命令获取CPU信息,不同操作系统的命令不同。

Linux/Unix:在Linux/Unix系统中,可以使用命令nproc获取CPU核数。

示例代码如下:Process process = Runtime.getRuntime().exec('nproc');BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));String line = reader.readLine();System.out.println('CPU核数:' + line.trim());Windows:在Windows系统中,可以使用命令wmic获取CPU信息。

示例代码如下:Process process = Runtime.getRuntime().exec('wmic cpu get NumberOfCores');BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));String line = reader.readLine();line = reader.readLine();System.out.println('CPU核数:' + line);以上是获取CPU核数的两种常用方法,可以根据实际需要选择合适的方法。

java获得CPU使用率

java获得CPU使用率,系统内存,虚拟机内存等情况(不用JNI)2009年10月23日星期五16:30在Java中,可以获得总的物理内存、剩余的物理内存、已使用的物理内存等信息,下面例子可以取得这些信息,并且获得在Windows下的内存使用率。

首先编写一个MonitorInfoBean类,用来装载监控的一些信息,包括物理内存、剩余的物理内存、已使用的物理内存、内存使用率等字段,该类的代码如下:package com.hmw.system.monitor;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) {edMemory = usedMemory;}public double getCpuRatio() {return cpuRatio;}public void setCpuRatio(double cpuRatio) {this.cpuRatio = cpuRatio;}}接着编写一个获得当前的监控信息的接口,该类的代码如下所示:package com.hmw.system.monitor;/*** 获取系统信息的业务逻辑类接口.*/public interface IMonitorService {/*** 获得当前的监控对象.* @return 返回构造好的监控对象* @throws Exception*/public MonitorInfoBean getMonitorInfoBean() throws Exception; }该类的实现类MonitorServiceImpl如下所示:package com.hmw.system.monitor;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.LineNumberReader;import java.util.StringTokenizer;import sun.management.ManagementFactory;import com.sun.management.OperatingSystemMXBean;/**** 获取系统信息的业务逻辑实现类.** @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 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("");// 总的物理内存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 = 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 getCaption,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,WriteOperationString caption = Bytes.substring(line, capidx, cmdidx - 1).trim();String cmd = Bytes.substring(line, cmdidx, kmtidx - 1).trim();if (cmd.indexOf("wmic.exe") >= 0) {continue;}String s1 = Bytes.substring(line, kmtidx, rocidx - 1).trim();String s2 = Bytes.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;}/*** 测试方法.** @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");}}该实现类中需要用到一个自己编写byte的工具类,该类的代码如下所示:package com.hmw.system.monitor;/*** byte操作类.*/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;}}运行下MonitorBeanImpl类,读者将会看到当前的内存、cpu利用率等信息。

java获取当前虚拟机机器码的方法

一、介绍在Java程序中,有时候我们需要获取当前虚拟机的机器码(也称为机器标识符或机器ID),以便进行一些特定的操作,比如程序的授权验证、硬件特定的操作等。

本文将介绍几种获取当前虚拟机机器码的方法。

二、通过Java代码获取机器码1. 使用InetAddress类获取主机名在Java中,可以使用InetAddress类的getLocalHost()方法来获取本地主机名。

主机名通常会包含机器码的一部分。

以下是一个示例代码:```javaimport .InetAddress;import .UnknownHostException;public class GetMachineCode {public static void m本人n(String[] args) {try {InetAddress address = InetAddress.getLocalHost();String hostName = address.getHostName();System.out.println("Host Name: " + hostName);} catch (UnknownHostException e) {e.printStackTrace();}}}```2. 通过System类获取环境变量Java中的System类提供了一些方法来获取系统环境变量,其中包括主机的一些信息,比如用户名、计算机名等。

以下是一个示例代码:```javapublic class GetSystemInfo {public static void m本人n(String[] args) {String osName = System.getProperty("");String userName = System.getProperty("");String userDir = System.getProperty("user.dir");String userHome = System.getProperty("user.home");System.out.println("OS Name: " + osName);System.out.println("User Name: " + userName);System.out.println("User Dir: " + userDir);System.out.println("User Home: " + userHome);}```3. 通过JNI调用本地方法如果以上方法不能满足需求,还可以通过JNI(Java Native Interface)调用本地方法来获取机器码。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

(原创)JA V A读取硬件信息(MAC地址,CPU号,硬盘卷标,CPU型号及CPU使用率等信息)(2011-03-27 00:16:12)转载分类:java开发标签:java读mac地址cpu号硬盘卷标cpu型号cpu使用率等杂谈在发布新版的MYPM时,加密要用到相关硬件信息,于是写了下面的测试类运行main 打印信息如下图需要引用的包sigar-1.6.3.jar及相关动态库测试时我加载了sigar自带所有动态库详见main方法内package mon.util;import java.io.BufferedReader;import java.io.File;import java.io.FileWriter;import java.io.InputStreamReader;import org.hyperic.sigar.CpuPerc;import org.hyperic.sigar.Sigar;import org.hyperic.sigar.SigarException;import org.hyperic.sigar.SigarLoader;import org.hyperic.sigar.cmd.Shell;import org.hyperic.sigar.cmd.SigarCommandBase; public class CpuInfo extends SigarCommandBase { public boolean displayTimes = true;public CpuInfo(Shell shell) {super(shell);}public CpuInfo() {super();}public String getUsageShort() {return "Display cpu information";}private void output(CpuPerc cpu) {println("User Time....." + CpuPerc.format(cpu.getUser()));println("Sys Time......" + CpuPerc.format(cpu.getSys()));println("Idle Time....." + CpuPerc.format(cpu.getIdle()));println("Wait Time....." + CpuPerc.format(cpu.getWait()));println("Nice Time....." + CpuPerc.format(cpu.getNice()));println("Combined......" + CpuPerc.format(cpu.getCombined()));println("Irq Time......" + CpuPerc.format(cpu.getIrq()));if (SigarLoader.IS_LINUX) {println("SoftIrq Time.." + CpuPerc.format(cpu.getSoftIrq()));println("Stolen Time...." + CpuPerc.format(cpu.getStolen()));}println("");}public void output(String[] args) throws SigarException {org.hyperic.sigar.CpuInfo[] infos = this.sigar.getCpuInfoList();CpuPerc[] cpus = this.sigar.getCpuPercList();org.hyperic.sigar.CpuInfo info = infos[0];long cacheSize = info.getCacheSize();println("Vendor........." + info.getVendor());println("Model.........." + info.getModel());println("Mhz............" + info.getMhz());println("Total CPUs....." + info.getTotalCores());if ((info.getTotalCores() != info.getTotalSockets()) || (info.getCoresPerSocket() > info.getTotalCores())) {println("Physical CPUs.." + info.getTotalSockets());println("Cores per CPU.." + info.getCoresPerSocket());}if (cacheSize != Sigar.FIELD_NOTIMPL) {println("Cache size...." + cacheSize);}println("");if (!this.displayTimes) {return;}for (int i = 0; i < cpus.length; i++) {println("CPU " + i + ".........");output(cpus[i]);}println("Totals........");output(this.sigar.getCpuPerc());StringBuffer sb=new StringBuffer("cpu号="+getCPUSerial()+"\n");String[] interfaces = sigar.getNetInterfaceList();if(interfaces!=null || interfaces.length>0)sb.append("第一个网卡号="+sigar.getNetInterfaceConfig(interfaces[0]).getHwaddr());org.hyperic.sigar.FileSystem[] filesystems = sigar.getFileSystemList();if(filesystems!=null || filesystems.length>0)sb.append("\n"+"硬盘第一个分区的卷标="+getHDSerial(filesystems[1].getDevName()));System.out.println(sb.toString());}public static void main(String[] args) throws Exception {//先加载siga动太库在不同的平台只要加载特定的动态库,这里我就全加载不区分了//在IDE环境中,可以不加载动态库设置natinve lib patch location 既可File nativeDir = new File("E:\\mypm10_new\\mypmdoc\\WebRoot\\WEB-INF\\native");File[] libs = nativeDir.listFiles();for (int i = 0; i < libs.length; i++) {if (libs[i].isFile())try {System.load(new File(nativeDir, libs[i].getName()).getPath());} catch (Throwable t) {}}new CpuInfo().processCommand(args);}public static double getCpuIdle() {try {sigar = new Sigar();return sigar.getCpuPerc().getIdle();} catch (Throwable t) {t.printStackTrace();} finally {if (sigar != null)sigar.close();}return 0;}public static String getHDSerial(String drive) {String result = "";try {File file = File.createTempFile("tmp", ".vbs");file.deleteOnExit();FileWriter fw = new java.io.FileWriter(file);String vbs = "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\n"+ "Set colDrives = objFSO.Drives\n" + "Set objDrive = colDrives.item(\"" + drive + "\")\n"+ "Wscript.Echo objDrive.SerialNumber";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();file.delete();} catch (Exception e) {}if (result.trim().length() < 1 || result == null) {result = "无磁盘ID被读取";}}public static String getCPUSerial() {String result = "";try {File file = File.createTempFile("tmp", ".vbs");file.deleteOnExit();FileWriter fw = new java.io.FileWriter(file);String vbs = "On Error Resume Next \r\n\r\n" + "strComputer = \".\" \r\n"+ "Set objWMIService = GetObject(\"winmgmts:\" _ \r\n"+ " & \"{impersonationLevel=impersonate}!\\\\\" & strComputer & \"\\root\\cimv2\") \r\n"+ "Set colItems = objWMIService.ExecQuery(\"Select * from Win32_Processor\") \r\n "+ "For Each objItem in colItems\r\n " + " Wscript.Echo objItem.ProcessorId \r\n "+ " exit for ' do the first cpu only! \r\n" + "Next ";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();file.delete();} catch (Exception e) {e.fillInStackTrace();}if (result.trim().length() < 1 || result == null) {result = "无CPU_ID被读取";}return result.trim();}}。

相关文档
最新文档