原理
通过linux cat命令查看/proc/cpuinfo文件,再使用正则表达式从中提取CpuID信息。
linux命令为:
cat /proc/cpuinfo
返回信息如下面格式:
Processor : ARMv7 Processor rev 2 (v7l) BogoMIPS : 99.40 Features : swp half thumb fastmult vfp edsp thumbee neon vfpv3 CPU implementer : 0x41 CPU architecture : 7 CPU variant : 0x2 CPU part : 0xc08 CPU revision : 2 Hardware : herring Revision : 000b Serial : 123456789abcdef
如果是在命令行还可以用grep进一步过滤输出:
cat /proc/cpuinfo|grep -i serial
但是如果在程序中过滤将得不到正确的输出。
程序
public static String getCpuID()
{
StringBuffer output = new StringBuffer();
try
{
Process process = Runtime.getRuntime().exec("cat /proc/cpuinfo");
DataInputStream stdout = new DataInputStream(process.getInputStream());
String line;
while ((line = stdout.readLine()) != null)
{
output.append(line).append('\n');
}
process.waitFor();
} catch (Exception e) {
output.append('\n').append(e.toString());
}
String regex = "Serial[\\s]{0,}:[\\s]{0,}([0-9,a-z,A-Z]{1,})$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(output.toString());
boolean ret = matcher.find();
if(ret)
return matcher.group(1);
return "获取失败";
}
登录为: 读者 (reader)