Java程序如果需要获取系统的硬件信息,如CPU、硬盘序列号,网卡MAC地址等,一般需要使用JNI程序调用,不过还有另外一种方法也可以实现这个功能,并且不需要JNI调用,原理是根据操作系统调用系统命令command,再根据命令行返回的信息分析获取硬件信息,这个方法需要程序判断操作系统类型来进行相应的调用,可以调用任何操作系统提供的命令,下面是Windows下面获取网卡MAC地址的例子:
public void testGetSysInfo() {
String address = "";
String os = System.getProperty("os.name");
if (os != null && os.startsWith("Windows")) {
try {
String command = "cmd.exe /c ipconfig /all";
Process p = Runtime.getRuntime().exec(command);
BufferedReader br = new BufferedReader(new InputStreamReader(p
.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
if (line.indexOf("Physical Address") > 0) {
int index = line.indexOf(":");
index += 2;
address = line.substring(index);
break;
}
}
br.close();
logger.info("mac address:" + address.trim());
} catch (IOException e) {
logger.info("Error:" + e);
}
}
}