我想使用java代码获取Windows序列号但是通过异常。 我的java代码正在使用某些版本的windows(7,8)而不能在windows 10 pro上运行,并且在相同的代码中抛出异常(未在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;
}
答案 0 :(得分:0)
我遇到了同样的问题。我设法通过在启动它之前明确指定进程必须在其中运行的目录来解决此问题:
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;
}