我想使用java代码获取Windows序列号,但通过异常。我的 java 代码在某些版本的 Windows (7,8( 上运行,不适用于 Windows 10 专业版,并且为相同的代码抛出了异常(未在 Windows vista 上验证(。
public String getWindowKey() {
String keydata = "";
try {
Process process = Runtime.getRuntime().exec(new String[]{"wmic", "diskdrive", "get", "serialnumber"});
process.getOutputStream().close();
BufferedReader input
= new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
String result = "";
while ((line = input.readLine()) != null) {
line = line.trim();
if (line.equalsIgnoreCase("SerialNumber")) {
continue;
}
result += line;
}
input.close();
// String[][] Key = {{"WindowKey", result}};
keydata = result;
} catch (Exception ex) {
LErrorDataLog.info("Exception :" + ex.getMessage());
}
return keydata;
}
我遇到了同样的问题。在启动进程之前,我设法通过显式指定进程必须在其中运行的目录来解决此问题:
List<String> cmd = new ArrayList<String>() {{
add("WMIC.exe"); add("diskdrive"); add("get"); add("serialNumber");
}};
ProcessBuilder pb = new ProcessBuilder().directory(getExecDir());
Process p = pb.command(cmd).start();
// Other code here
getExecDir()
方法如下所示:
/**
* Get the execution directory for WMIC
* @return File object pointing to the execution directory
* @throws IOException Execution directory doesn't exist
*/
private static File getExecDir() throws IOException {
String root = System.getenv("SystemRoot");
File dir = new File(root, "System32" + File.separatorChar + "wbem");
if (!dir.exists() || !dir.isDirectory()) {
throw new IOException('"' + dir.getAbsolutePath() + "" does not exist or is not a directory!");
}
return dir;
}