java读取硬件信息
- 格式:doc
- 大小:114.00 KB
- 文档页数:6
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程序读取服务器端数据文件的方法
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和内存的使用情况。
这些信息对于优化程序性能和资源管理非常重要。
以下是两种常用的方法: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库。
它提供了一些用于查询操作系统和硬件信息的方法,可以帮助开发人员更好地了解和管理系统。
这个库可以用于开发各种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读取外部配置文件的方法。
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,内存,硬盘,进程)的相关方法一、这是一个获取相关信息的简单的方法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作为一种广泛使用的编程语言,具有强大的跨评台能力和丰富的库支持,因此在网络编程中也有着广泛的应用。
在实际开发中,我们经常需要获取指定服务器信息,比如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 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使用率,系统内存,虚拟机内存等情况(不用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程序中,有时候我们需要获取当前虚拟机的机器码(也称为机器标识符或机器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. 使用系统命令获取信息。
在Windows系统中,可以使用
'systeminfo'命令获取计算机的系统信息,包括操作系统版本、CPU 型号、内存大小等。
在Linux系统中,可以使用'lshw'命令获取硬件信息,包括CPU型号、内存大小、硬盘大小等。
2. 使用WMI获取信息。
WMI(Windows Management Instrumentation)是一种面向对象的API,用于管理Windows操作系统。
通过WMI可以获取计算机的硬件信息,如CPU型号、内存大小、硬盘大小等。
3. 使用第三方库获取信息。
有许多第三方库可以获取计算机的硬件信息,如CPU-Z、GPU-Z、Speccy等。
这些库可以提供更详细的硬件信息,如CPU的核心数、显卡的型号等。
4. 使用编程语言自带的方法获取信息。
许多编程语言都提供了获取硬件信息的方法,如Java中的Runtime类和System类,C#中的System.Management命名空间等。
无论采用哪种方法,获取硬件信息都需要特定的权限。
在Windows 系统中,需要以管理员身份运行程序;在Linux系统中,需要使用root权限运行程序。
同时,由于硬件信息的获取可能会损害系统的稳定性,因此需要谨慎使用。
- 1 -。
在网络和软件开发领域,获取客户端机器码是一项常见的任务。
在Java编程中,我们也经常会遇到这样的需求,需要获取客户端机器码来进行识别、验证或其他操作。
那么,在Java中,我们该如何获取客户端机器码呢?本文将从深度和广度两个方面来探讨这个主题。
1. 基本概念我们需要了解客户端机器码的基本概念。
客户端机器码通常是指客户端设备的唯一标识,它可以用于识别客户端设备或验证客户端的合法性。
通常情况下,客户端机器码是由客户端设备的硬件或软件信息计算而来的,具有唯一性和不可变性。
2. Java中的实现在Java中,获取客户端机器码的方法有很多种,我们可以根据具体的需求来选择合适的方法。
常见的方法包括获取MAC位置区域、获取硬件信息、获取系统信息等。
在以下内容中,我将逐一介绍这些方法,并分析它们的优缺点。
2.1 获取MAC位置区域MAC位置区域是网卡设备的唯一标识,可以用于识别设备。
在Java 中,我们可以通过调用操作系统的命令来获取MAC位置区域,然后进行处理和格式化,最终得到客户端的机器码。
2.2 获取硬件信息除了MAC位置区域外,我们还可以通过获取客户端设备的硬件信息来生成机器码。
这些硬件信息可以包括CPU型号、硬盘序列号、主板型号等。
通过这些信息的组合,我们可以得到一个较为唯一的机器码。
2.3 获取系统信息获取客户端设备的系统信息也是一种常见的方法。
这包括操作系统版本、系统语言、时区等信息。
这些信息的组合可能会更加唯一和具有区分度。
3. 个人观点与理解在实际应用中,选择合适的方法来获取客户端机器码非常重要。
我们需要根据具体的业务需求、安全性考量和用户隐私保护等方面来综合考虑。
我们还需要注意到,客户端机器码可能受到用户干预、设备更换或者虚拟化环境的影响,这也需要我们在设计和使用时加以考虑。
4. 总结获取客户端机器码在Java开发中是一项具有挑战性的任务。
我们需要根据具体需求选择合适的方法,并在实际应用中注意到安全性和合法性的问题。
JAVA通过oshi获取系统和硬件信息⼀、引⼊jar包<dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>RELEASE</version></dependency><!-- https:///artifact/com.github.oshi/oshi-core --><dependency><groupId>com.github.oshi</groupId><artifactId>oshi-core</artifactId><version>3.5.0</version></dependency>⼆、测试代码import org.slf4j.Logger;import org.slf4j.LoggerFactory;import oshi.SystemInfo;import oshi.hardware.*;import oshi.hardware.CentralProcessor.TickType;import oshi.software.os.*;import oshi.software.os.OperatingSystem.ProcessSort;import oshi.util.FormatUtil;import oshi.util.Util;import java.util.Arrays;import java.util.List;/*** The Class SystemInfoTest.** @author dblock[at]dblock[dot]org*/public class SystemInfoTest {/*** The main method.** @param args the arguments*/public static void main(String[] args) {// Options: ERROR > WARN > INFO > DEBUG > TRACELogger LOG = LoggerFactory.getLogger(SystemInfoTest.class);("Initializing System...");SystemInfo si = new SystemInfo();HardwareAbstractionLayer hal = si.getHardware();OperatingSystem os = si.getOperatingSystem();System.out.println(os);("Checking computer system...");printComputerSystem(hal.getComputerSystem());("Checking Processor...");printProcessor(hal.getProcessor());("Checking Memory...");printMemory(hal.getMemory());("Checking CPU...");printCpu(hal.getProcessor());("Checking Processes...");printProcesses(os, hal.getMemory());("Checking Sensors...");printSensors(hal.getSensors());("Checking Power sources...");printPowerSources(hal.getPowerSources());("Checking Disks...");printDisks(hal.getDiskStores());("Checking File System...");printFileSystem(os.getFileSystem());("Checking Network interfaces...");printNetworkInterfaces(hal.getNetworkIFs());("Checking Network parameterss...");printNetworkParameters(os.getNetworkParams());// hardware: displays("Checking Displays...");printDisplays(hal.getDisplays());// hardware: USB devices("Checking USB Devices...");printUsbDevices(hal.getUsbDevices(true));}private static void printComputerSystem(final ComputerSystem computerSystem) {System.out.println("manufacturer: " + computerSystem.getManufacturer());System.out.println("model: " + computerSystem.getModel());System.out.println("serialnumber: " + computerSystem.getSerialNumber());final Firmware firmware = computerSystem.getFirmware();System.out.println("firmware:");System.out.println(" manufacturer: " + firmware.getManufacturer());System.out.println(" name: " + firmware.getName());System.out.println(" description: " + firmware.getDescription());System.out.println(" version: " + firmware.getVersion());System.out.println(" release date: " + (firmware.getReleaseDate() == null ? "unknown": firmware.getReleaseDate() == null ? "unknown" : FormatUtil.formatDate(firmware.getReleaseDate())));final Baseboard baseboard = computerSystem.getBaseboard();System.out.println("baseboard:");System.out.println(" manufacturer: " + baseboard.getManufacturer());System.out.println(" model: " + baseboard.getModel());System.out.println(" version: " + baseboard.getVersion());System.out.println(" serialnumber: " + baseboard.getSerialNumber());}private static void printProcessor(CentralProcessor processor) {System.out.println(processor);System.out.println(" " + processor.getPhysicalPackageCount() + " physical CPU package(s)");System.out.println(" " + processor.getPhysicalProcessorCount() + " physical CPU core(s)");System.out.println(" " + processor.getLogicalProcessorCount() + " logical CPU(s)");System.out.println("Identifier: " + processor.getIdentifier());System.out.println("ProcessorID: " + processor.getProcessorID());}private static void printMemory(GlobalMemory memory) {System.out.println("Memory: " + FormatUtil.formatBytes(memory.getAvailable()) + "/"+ FormatUtil.formatBytes(memory.getTotal()));System.out.println("Swap used: " + FormatUtil.formatBytes(memory.getSwapUsed()) + "/"+ FormatUtil.formatBytes(memory.getSwapTotal()));}private static void printCpu(CentralProcessor processor) {System.out.println("Uptime: " + FormatUtil.formatElapsedSecs(processor.getSystemUptime()));System.out.println("Context Switches/Interrupts: " + processor.getContextSwitches() + " / " + processor.getInterrupts());long[] prevTicks = processor.getSystemCpuLoadTicks();System.out.println("CPU, IOWait, and IRQ ticks @ 0 sec:" + Arrays.toString(prevTicks));// Wait a second...Util.sleep(1000);long[] ticks = processor.getSystemCpuLoadTicks();System.out.println("CPU, IOWait, and IRQ ticks @ 1 sec:" + Arrays.toString(ticks));long user = ticks[ER.getIndex()] - prevTicks[ER.getIndex()];long nice = ticks[TickType.NICE.getIndex()] - prevTicks[TickType.NICE.getIndex()];long sys = ticks[TickType.SYSTEM.getIndex()] - prevTicks[TickType.SYSTEM.getIndex()];long idle = ticks[TickType.IDLE.getIndex()] - prevTicks[TickType.IDLE.getIndex()];long iowait = ticks[TickType.IOWAIT.getIndex()] - prevTicks[TickType.IOWAIT.getIndex()];long irq = ticks[TickType.IRQ.getIndex()] - prevTicks[TickType.IRQ.getIndex()];long softirq = ticks[TickType.SOFTIRQ.getIndex()] - prevTicks[TickType.SOFTIRQ.getIndex()];long steal = ticks[TickType.STEAL.getIndex()] - prevTicks[TickType.STEAL.getIndex()];long totalCpu = user + nice + sys + idle + iowait + irq + softirq + steal;System.out.format("User: %.1f%% Nice: %.1f%% System: %.1f%% Idle: %.1f%% IOwait: %.1f%% IRQ: %.1f%% SoftIRQ: %.1f%% Steal: %.1f%%%n", 100d * user / totalCpu, 100d * nice / totalCpu, 100d * sys / totalCpu, 100d * idle / totalCpu,100d * iowait / totalCpu, 100d * irq / totalCpu, 100d * softirq / totalCpu, 100d * steal / totalCpu);System.out.format("CPU load: %.1f%% (counting ticks)%n", processor.getSystemCpuLoadBetweenTicks() * 100);System.out.format("CPU load: %.1f%% (OS MXBean)%n", processor.getSystemCpuLoad() * 100);double[] loadAverage = processor.getSystemLoadAverage(3);System.out.println("CPU load averages:" + (loadAverage[0] < 0 ? " N/A" : String.format(" %.2f", loadAverage[0]))+ (loadAverage[1] < 0 ? " N/A" : String.format(" %.2f", loadAverage[1]))+ (loadAverage[2] < 0 ? " N/A" : String.format(" %.2f", loadAverage[2])));// per core CPUStringBuilder procCpu = new StringBuilder("CPU load per processor:");double[] load = processor.getProcessorCpuLoadBetweenTicks();for (double avg : load) {procCpu.append(String.format(" %.1f%%", avg * 100));}System.out.println(procCpu.toString());}private static void printProcesses(OperatingSystem os, GlobalMemory memory) {System.out.println("Processes: " + os.getProcessCount() + ", Threads: " + os.getThreadCount());// Sort by highest CPUList<OSProcess> procs = Arrays.asList(os.getProcesses(5, ProcessSort.CPU));System.out.println(" PID %CPU %MEM VSZ RSS Name");for (int i = 0; i < procs.size() && i < 5; i++) {OSProcess p = procs.get(i);System.out.format(" %5d %5.1f %4.1f %9s %9s %s%n", p.getProcessID(),100d * (p.getKernelTime() + p.getUserTime()) / p.getUpTime(),100d * p.getResidentSetSize() / memory.getTotal(), FormatUtil.formatBytes(p.getVirtualSize()),FormatUtil.formatBytes(p.getResidentSetSize()), p.getName());}}private static void printSensors(Sensors sensors) {System.out.println("Sensors:");System.out.format(" CPU Temperature: %.1f°C%n", sensors.getCpuTemperature());System.out.println(" Fan Speeds: " + Arrays.toString(sensors.getFanSpeeds()));System.out.format(" CPU Voltage: %.1fV%n", sensors.getCpuVoltage());}private static void printPowerSources(PowerSource[] powerSources) {StringBuilder sb = new StringBuilder("Power: ");if (powerSources.length == 0) {sb.append("Unknown");} else {double timeRemaining = powerSources[0].getTimeRemaining();if (timeRemaining < -1d) {sb.append("Charging");} else if (timeRemaining < 0d) {sb.append("Calculating time remaining");} else {sb.append(String.format("%d:%02d remaining", (int) (timeRemaining / 3600),(int) (timeRemaining / 60) % 60));}}for (PowerSource pSource : powerSources) {sb.append(String.format("%n %s @ %.1f%%", pSource.getName(), pSource.getRemainingCapacity() * 100d)); }System.out.println(sb.toString());}private static void printDisks(HWDiskStore[] diskStores) {System.out.println("Disks:");for (HWDiskStore disk : diskStores) {boolean readwrite = disk.getReads() > 0 || disk.getWrites() > 0;System.out.format(" %s: (model: %s - S/N: %s) size: %s, reads: %s (%s), writes: %s (%s), xfer: %s ms%n", disk.getName(), disk.getModel(), disk.getSerial(),disk.getSize() > 0 ? FormatUtil.formatBytesDecimal(disk.getSize()) : "?",readwrite ? disk.getReads() : "?", readwrite ? FormatUtil.formatBytes(disk.getReadBytes()) : "?",readwrite ? disk.getWrites() : "?", readwrite ? FormatUtil.formatBytes(disk.getWriteBytes()) : "?",readwrite ? disk.getTransferTime() : "?");HWPartition[] partitions = disk.getPartitions();if (partitions == null) {// TODO Remove when all OS's implementedcontinue;}for (HWPartition part : partitions) {System.out.format(" |-- %s: %s (%s) Maj:Min=%d:%d, size: %s%s%n", part.getIdentification(),part.getName(), part.getType(), part.getMajor(), part.getMinor(),FormatUtil.formatBytesDecimal(part.getSize()),part.getMountPoint().isEmpty() ? "" : " @ " + part.getMountPoint());}}}private static void printFileSystem(FileSystem fileSystem) {System.out.println("File System:");System.out.format(" File Descriptors: %d/%d%n", fileSystem.getOpenFileDescriptors(),fileSystem.getMaxFileDescriptors());OSFileStore[] fsArray = fileSystem.getFileStores();for (OSFileStore fs : fsArray) {long usable = fs.getUsableSpace();long total = fs.getTotalSpace();System.out.format(" %s (%s) [%s] %s of %s free (%.1f%%) is %s "+ (fs.getLogicalVolume() != null && fs.getLogicalVolume().length() > 0 ? "[%s]" : "%s")+ " and is mounted at %s%n",fs.getName(), fs.getDescription().isEmpty() ? "file system" : fs.getDescription(), fs.getType(),FormatUtil.formatBytes(usable), FormatUtil.formatBytes(fs.getTotalSpace()), 100d * usable / total,fs.getVolume(), fs.getLogicalVolume(), fs.getMount());}}private static void printNetworkInterfaces(NetworkIF[] networkIFs) {System.out.println("Network interfaces:");for (NetworkIF net : networkIFs) {System.out.format(" Name: %s (%s)%n", net.getName(), net.getDisplayName());System.out.format(" MAC Address: %s %n", net.getMacaddr());System.out.format(" MTU: %s, Speed: %s %n", net.getMTU(), FormatUtil.formatValue(net.getSpeed(), "bps")); System.out.format(" IPv4: %s %n", Arrays.toString(net.getIPv4addr()));System.out.format(" IPv6: %s %n", Arrays.toString(net.getIPv6addr()));boolean hasData = net.getBytesRecv() > 0 || net.getBytesSent() > 0 || net.getPacketsRecv() > 0|| net.getPacketsSent() > 0;System.out.format(" Traffic: received %s/%s%s; transmitted %s/%s%s %n",hasData ? net.getPacketsRecv() + " packets" : "?",hasData ? FormatUtil.formatBytes(net.getBytesRecv()) : "?",hasData ? " (" + net.getInErrors() + " err)" : "",hasData ? net.getPacketsSent() + " packets" : "?",hasData ? FormatUtil.formatBytes(net.getBytesSent()) : "?",hasData ? " (" + net.getOutErrors() + " err)" : "");}}private static void printNetworkParameters(NetworkParams networkParams) {System.out.println("Network parameters:");System.out.format(" Host name: %s%n", networkParams.getHostName());System.out.format(" Domain name: %s%n", networkParams.getDomainName());System.out.format(" DNS servers: %s%n", Arrays.toString(networkParams.getDnsServers()));System.out.format(" IPv4 Gateway: %s%n", networkParams.getIpv4DefaultGateway());System.out.format(" IPv6 Gateway: %s%n", networkParams.getIpv6DefaultGateway());}private static void printDisplays(Display[] displays) {System.out.println("Displays:");int i = 0;for (Display display : displays) {System.out.println(" Display " + i + ":");System.out.println(display.toString());i++;}}private static void printUsbDevices(UsbDevice[] usbDevices) {System.out.println("USB Devices:");for (UsbDevice usbDevice : usbDevices) {System.out.println(usbDevice.toString());}}}三、结果Microsoft Windows 10 build 15063manufacturer: LENOVOmodel: 80RUserialnumber: R90LN08UR9N0B6922009firmware:manufacturer: LENOVOname: E5CN53WWdescription: E5CN53WWversion: LENOVO - 0release date: 07/11/2016baseboard:manufacturer: LENOVOmodel: unknownversion: SDK0K09938 WINserialnumber: R90LN08UIntel(R) Core(TM) i5-6300HQ CPU @ 2.30GHz1 physical CPU package(s)4 physical CPU core(s)4 logical CPU(s)Identifier: Intel64 Family 6 Model 94 Stepping 3ProcessorID: BFEBFBFF000506E3Memory: 1.5 GiB/7.8 GiBSwap used: 84.4 MiB/6.3 GiBUptime: 1 days, 11:45:25Context Switches/Interrupts: 648525190 / 338012494CPU, IOWait, and IRQ ticks @ 0 sec:[18421421, 0, 10068431, 288934828, 0, 266351, 143296, 0]CPU, IOWait, and IRQ ticks @ 1 sec:[18421578, 0, 10068486, 288938671, 0, 266351, 143304, 0]User: 3.9% Nice: 0.0% System: 1.4% Idle: 94.6% IOwait: 0.0% IRQ: 0.0% SoftIRQ: 0.2% Steal: 0.0%CPU load: 13.0% (counting ticks)CPU load: 17.4% (OS MXBean)CPU load averages: N/A N/A N/ACPU load per processor: 19.3% 12.8% 12.8% 12.8%Processes: 184, Threads: 2447PID %CPU %MEM VSZ RSS Name0 100.0 0.0 64 KiB 8 KiB System Idle Process5416 10.0 1.6 3.4 GiB 130.4 MiB java.exe12676 8.8 1.3 2.1 GiB 104.9 MiB java.exe11988 5.8 16.8 3.3 GiB 1.3 GiB idea64.exe5312 4.4 1.3 2.0 TiB 101.4 MiB chrome.exeSensors:CPU Temperature: 42.0°CFan Speeds: [0]CPU Voltage: 0.0VPower: ChargingSystem Battery @ 96.6%Disks:\\.\PHYSICALDRIVE0: (model: SanDisk SD7SN6S128G (标准磁盘驱动器) - S/N: 161416401094) size: 128.0 GB, reads: 1117123 (33.4 GiB), writes: 703948 (21.2 GiB), xfer: 2570354 ms|-- 磁盘 #0,分区 #0: GPT: Basic Data (GPT: 基本数据) Maj:Min=0:0, size: 471.9 MB @ F:\|-- 磁盘 #0,分区 #1: GPT: System (GPT: 系统) Maj:Min=0:1, size: 104.9 MB|-- 磁盘 #0,分区 #2: GPT: Basic Data (GPT: 基本数据) Maj:Min=0:2, size: 126.6 GB @ C:\|-- 磁盘 #0,分区 #3: GPT: Basic Data (GPT: 基本数据) Maj:Min=0:3, size: 845.2 MB @ G:\\\.\PHYSICALDRIVE1: (model: WDC WD10SPCX-24HWST1 (标准磁盘驱动器) - S/N: WD-WX31A86F35XC) size: 1.0 TB, reads: 379263 (6.0 GiB), writes: 103105 (2.6 GiB), xfer: 4014792 ms |-- 磁盘 #1,分区 #0: GPT: Basic Data (GPT: 基本数据) Maj:Min=1:0, size: 475.9 GB @ D:\|-- 磁盘 #1,分区 #1: GPT: Basic Data (GPT: 基本数据) Maj:Min=1:1, size: 524.3 GB @ E:\File System:File Descriptors: 0/0本地固定磁盘 (F:) (Fixed drive) [NTFS] 436.1 MiB of 450.0 MiB free (96.9%) is \\?\Volume{9afc85a4-9f44-11e7-ab77-a5dc01376557}\ and is mounted at F:\本地固定磁盘 (C:) (Fixed drive) [NTFS] 12.9 GiB of 117.9 GiB free (11.0%) is \\?\Volume{01a1a160-fbb4-49c7-be19-6dd52882bcbc}\ and is mounted at C:\本地固定磁盘 (G:) (Fixed drive) [NTFS] 303.4 MiB of 806.0 MiB free (37.6%) is \\?\Volume{9afc85a5-9f44-11e7-ab77-a5dc01376557}\ and is mounted at G:\本地固定磁盘 (D:) (Fixed drive) [NTFS] 161.8 GiB of 443.2 GiB free (36.5%) is \\?\Volume{a287f045-a9ac-4669-ab44-bdbd74692600}\ and is mounted at D:\本地固定磁盘 (E:) (Fixed drive) [NTFS] 246.0 GiB of 488.3 GiB free (50.4%) is \\?\Volume{84c6da35-38e7-457e-b528-c12da6ed2898}\ and is mounted at E:\Network interfaces:Name: wlan0 (Microsoft Wi-Fi Direct Virtual Adapter)MAC Address: 84:ef:18:36:4c:abMTU: 1500, Speed: 0 bpsIPv4: []IPv6: [fe80:0:0:0:55ed:790e:b70:ea43]Traffic: received ?/?; transmitted ?/?Name: net2 (Microsoft Teredo Tunneling Adapter)MAC Address: 00:00:00:00:00:00:00:e0MTU: 1280, Speed: 100 KbpsIPv4: []IPv6: [2001:0:9d38:6ab8:2446:2d3f:34a2:86f5, fe80:0:0:0:2446:2d3f:34a2:86f5]Traffic: received 15 packets/2.2 KiB (0 err); transmitted 1580 packets/209.9 KiB (0 err)Name: eth7 (Realtek PCIe GBE Family Controller)MAC Address: 54:ee:75:b0:ed:33MTU: 1500, Speed: 0 bpsIPv4: []IPv6: [fe80:0:0:0:d0:cff0:250f:34d0]Traffic: received ?/?; transmitted ?/?Name: wlan2 (Intel(R) Dual Band Wireless-AC 3165)MAC Address: 84:ef:18:36:4c:aaMTU: 1500, Speed: 72.2 MbpsIPv4: [172.16.3.132]IPv6: []Traffic: received 99670 packets/87.7 MiB (0 err); transmitted 68049 packets/14.9 MiB (0 err) Network parameters:Host name: Sindrol-NTBDomain name: Sindrol-NTBDNS servers: [202.106.0.20, 114.114.114.114]IPv4 Gateway: 172.16.3.254IPv6 Gateway: ::Displays:Display 0:Manuf. ID=BOE, Product ID=65d, Digital, Serial=00000000, ManufDate=1/2015, EDID v1.4 34 x 19 cm (13.4 x 7.5 in)Preferred Timing: Clock 141MHz, Active Pixels 1920x1080Manufacturer Data: 000000000000000000000000000000000000Unspecified Text: BOE HFUnspecified Text: NV156FHM-N42Display 1:Manuf. ID=AOC, Product ID=2476, Digital, Serial=00000319, ManufDate=5/2016, EDID v1.3 52 x 29 cm (20.5 x 11.4 in)Preferred Timing: Clock 148MHz, Active Pixels 1920x1080Range Limits: Field Rate 50-76 Hz vertical, 30-83 Hz horizontal, Max clock: 170 MHzMonitor Name: 2476WMSerial Number: E71G5BA000793USB Devices:Intel(R) USB 3.0 可扩展主机控制器 - 1.0 (Microsoft) (通⽤ USB xHCI 主机控制器)|-- USB 根集线器(USB 3.0) ((标准 USB 集线器))|-- Apple Mobile Device USB Driver (Apple, Inc.)|-- Apple iPhone (Apple Inc.)|-- USB Composite Device ((标准 USB 主控制器))|-- Lenovo EasyCamera (Bison)|-- USB Composite Device ((标准 USB 主控制器))|-- USB 输⼊设备 ((标准系统设备))|-- HID Keyboard Device ((标准键盘))|-- USB 输⼊设备 ((标准系统设备))|-- HID-compliant mouse (Microsoft)|-- 符合 HID 标准的供应商定义设备 ((标准系统设备))|-- 符合 HID 标准的⽤户控制设备 (Microsoft)|-- 符合 HID 标准的系统控制器 ((标准系统设备))|-- USB 输⼊设备 ((标准系统设备))|-- 符合 HID 标准的供应商定义设备 ((标准系统设备))|-- USB 输⼊设备 ((标准系统设备))|-- HID-compliant mouse (Microsoft)|-- 英特尔(R) ⽆线 Bluetooth(R) (Intel Corporation)。
JAVA中读写配置文件2007-12-22java中读写属性文件下面的文章来自CSDN hyde82的专栏,因为很实用,所以就摘下来放在此处,具体网址忘记啦.无论是有图形化的选项配置对话框,或者是系统提供的注册表,文本形式的本地配置文件依然是最牢靠、应用最广泛的配置信息保存形式。
配置信息的一般模式就是一个配置项对应一个值,前者一般是个字符串,后者可能是数字或者字符串或者别的什么。
在传统win32编程中有系统提供的api供我们解读.ini文件,后来也有操作注册表的封装好的api,在.net中更是有解读XML形式.config文件的现成方法。
在Java中,对配置文件的使用进行封装也是十分有意义的。
封装应该达到这样的效果:应用只管从配置信息进行按名读取值、设置值、保存等操作,而不需要关心具体以什么文件格式保存、如何解析。
文件格式(纯文本?XML?数据库?)、IO 方式(本地文件?远程文件?控制台流?)在封装类内部的变更,都不会影响应用对配置信息的感知。
从键名-值的对应关系以及文件的存取,我们最容易想到的就是java.util.Properties对象,他是HashTable的子类,保存的就是很多组键名-值的对应二原组,并提供快速的查询和直接的从文件读取、保存为文件的方法。
具体请参考相关文档,我们直接看程序。
首先自定义一个异常://ConfigurationException.javapackage configuration;public class ConfigurationException extends Exception{ public ConfigurationException(){}public ConfigurationException(String msg){super(msg);}}然后是我们的封装类://Configuration.javapackage configuration;import java.io.*;import java.util.*;import configuration.*;public class Configuration {private Properties config=new Properties();//记录配置项private String fn=null;//记录配置文件名//此构造方法用于新建配置文件public Configuration(){}//从指定文件名读入配置信息public Configuration(String fileName)throws ConfigurationException {try {FileInputStream fin = new FileInputStream(fileName); config.load(fin); //载入文件fin.close();}catch (IOException ex) {throw new ConfigurationException("无法读取指定的配置文件:"+fileName);}fn=fileName;}//指定配置项名称,返回配置值public String getValue(String itemName){return config.getProperty(itemName);}//指定配置项名称和默认值,返回配置值public String getValue(String itemName,String defaultValue){return config.getProperty(itemName,defaultValue);}//设置配置项名称及其值public void setValue(String itemName,String value){ config.setProperty(itemName,value);return;}//保存配置文件,指定文件名和抬头描述public void saveFile(String fileName,String description) throws ConfigurationException {try {FileOutputStream fout= new FileOutputStream(fileName);config.store(fout, description);//保存文件fout.close();}catch (IOExeption ex) {throw new ConfigurationException("无法保存指定的配置文件:"+fileName);}}//保存配置文件,指定文件名public void saveFile(String fileName)throws ConfigurationException {saveFile(fileName,"");}//保存配置文件,采用原文件名public void saveFile() throws ConfigurationException { if(fn.length()==0)throw new ConfigurationException("需指定保存的配置文件名");saveFile(fn);}}从这个封装类我们可以看到,实例化对象的时候我们可以指定一个文件名使得从中读取配置信息,通过getValue方法取得属性值,setValue方法设置属性值,saveFile方法保存文件。
java读取资源文件的方法Java是一种广泛应用于开发各种应用程序的编程语言。
在Java中,读取资源文件是一项常见的任务,它允许我们从外部文件中获取数据或配置信息。
本文将介绍几种常用的Java读取资源文件的方法。
一、使用ClassLoader读取资源文件Java中的ClassLoader是用于加载类的关键组件之一。
它不仅可以加载类,还可以加载其他类型的资源文件。
通过ClassLoader,我们可以很方便地读取资源文件。
我们需要使用ClassLoader的getResourceAsStream()方法获取资源文件的输入流。
这个方法可以接受一个相对路径作为参数,并返回一个InputStream对象。
然后,我们可以使用这个输入流来读取资源文件的内容。
下面是一个使用ClassLoader读取资源文件的示例代码:```javaClassLoader classLoader = getClass().getClassLoader(); InputStream inputStream = classLoader.getResourceAsStream("config.properties");```在上面的代码中,我们使用了getClass().getClassLoader()方法获取当前类的ClassLoader。
然后,我们调用getResourceAsStream()方法获取资源文件config.properties的输入流。
二、使用InputStream读取资源文件除了使用ClassLoader,我们还可以使用InputStream来读取资源文件。
这种方法适用于读取位于文件系统中的资源文件。
我们需要创建一个File对象,用于表示资源文件的路径。
然后,我们可以使用FileInputStream来打开这个文件,并获取其输入流。
最后,我们可以使用这个输入流来读取资源文件的内容。
下面是一个使用InputStream读取资源文件的示例代码:```javaFile file = new File("path/to/config.properties"); InputStream inputStream = new FileInputStream(file);```在上面的代码中,我们创建了一个File对象,表示资源文件config.properties的路径。
JAVA中通过oshi获取系统和硬件信息1.导⼊我们使⽤的依赖//maven 依赖//Java version: 1.8.0_66//Apache Maven 3.1.1<dependency><groupId>com.github.oshi</groupId><artifactId>oshi-core</artifactId><version>3.4.2</version></dependency>2.使⽤代码//获取硬件及内存的使⽤情况public static void getDiskInfo(){File[] disks = File.listRoots();for(File file : disks){System.out.print(file.getPath() + " ");System.out.print("空闲未使⽤ = " + file.getFreeSpace() / 1024 / 1024 + "M" + " ");// 空闲空间System.out.print("已经使⽤ = " + file.getUsableSpace() / 1024 / 1024 + "M" + " ");// 可⽤空间System.out.print("总容量 = " + file.getTotalSpace() / 1024 / 1024 + "M" + " ");// 总空间System.out.println();}}public static void getMemInfo(){OperatingSystemMXBean mem = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();System.out.println("Total RAM:" + mem.getTotalPhysicalMemorySize() / 1024 / 1024 + "MB");System.out.println("Available RAM:" + mem.getFreePhysicalMemorySize() / 1024 / 1024 + "MB");} 如有错误,请指正!联系wx 155********。
java获取linux系统cpu信息的方法要获取Linux系统的CPU信息,可以使用以下几种方法。
1.使用命令行工具-使用`cat /proc/cpuinfo`命令可以查看CPU的详细信息,包括型号、频率、核心数、缓存等。
-使用`lscpu`命令可以获取CPU的一些常见统计信息,如体系架构、字长、主频等。
-使用`top`命令可以实时查看系统的CPU使用率、进程状态等信息。
2.使用Java代码可以使用Java的ProcessBuilder类来执行命令行命令,并通过读取命令的输出获取CPU信息。
以下是一个示例代码:```javaimport java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.nio.charset.StandardCharsets;public class GetCpuInfo {public static void main(String[] args) {String command = "cat /proc/cpuinfo";try {ProcessBuilder processBuilder = newProcessBuilder(command);Process process = processBuilder.start();InputStream inputStream = process.getInputStream();BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));String line;while ((line = bufferedReader.readLine()) != null) {System.out.println(line);}bufferedReader.close();} catch (IOException e) {e.printStackTrace();}}}```此代码使用了ProcessBuilder来执行命令,并通过输入流读取命令输出的内容,然后逐行打印出来。
(原创)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();}}。