Java:读取Windows注册表项已停止工作
我一直在通过执行“reg查询”来读取键和值,但几天前它停止了工作。我没有更改任何代码。 读取键值仍然可以正常工作:Java:读取Windows注册表项已停止工作,java,applet,registry,Java,Applet,Registry,我一直在通过执行“reg查询”来读取键和值,但几天前它停止了工作。我没有更改任何代码。 读取键值仍然可以正常工作: Process process = Runtime.getRuntime().exec( "reg query " + "\"" + root + key + "\" /v " + valueName); InputStreamReader inputreader = new InputStreamReader(
Process process = Runtime.getRuntime().exec(
"reg query " + "\"" + root + key + "\" /v " + valueName);
InputStreamReader inputreader = new InputStreamReader(
process.getInputStream());
BufferedReader reader = new BufferedReader(inputreader);
process.waitFor();
String line = null;
while ((line = reader.readLine()) != null) {
if (line.contains("REG_SZ")) {
Pattern pattern = Pattern.compile("REG_SZ\\s*(.*)");
Matcher matcher = pattern.matcher(line);
while (matcher.find()) {
return line.substring(matcher.start(1));
}
} else if (line.contains("REG_DWORD")) {
Pattern pattern = Pattern.compile("REG_DWORD\\s*(.*)");
Matcher matcher = pattern.matcher(line);
while (matcher.find()) {
return line.substring(matcher.start(1));
}
}
}
但是读取键时的process.waitFor()永远不会返回。这一直有效到几天前:
Process process = Runtime.getRuntime().exec(
"reg query " + "\"" + root + key + "\"");
InputStreamReader inputreader = new InputStreamReader(
process.getInputStream());
BufferedReader reader = new BufferedReader(inputreader);
process.waitFor();
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(">>"+line);
if (line.contains(root)) {
list.add(line.substring(line.lastIndexOf('\\') + 1));
}
}
String[] keys = new String[list.size()];
return list.toArray(keys);
如果我使用windows命令行运行查询,它工作正常,因此不是我的查询出错。。。
我让小程序在服务器上运行,但两天前我们的外部测试人员报告,小程序被冻结。然而,它仍然在为我和我的同事工作。今天早上,它对我来说也冻结了,而且从…开始就不起作用了。通常,waitFor()
调用无法返回,因为子进程在写入时被阻塞
由于在运行reg
命令时,您没有使用该命令的输出,因此它可能已填充了输出缓冲区,并且它正在等待您读取一些输出,然后再写入更多
例如,如果向注册表项添加更多的值,这可能会中断以前有效的查询
我建议创建一个线程用于读取进程的标准输出流,另一个线程用于读取其标准错误流。当您读取所有输出时,标准输出流将发出EOF信号(这将导致BufferedReader
返回null
)
此时,对
waitFor()
的调用不应该阻塞(通常这不是一个安全的假设,但是reg
命令也可以)。最后,你应该destroy()
这个过程。这几天有什么事情发生吗?浏览器更新、操作系统更新、是否安装了修补程序?可能是任何东西,从防病毒到操作系统补丁再到浏览器更新。