我目前正在开发一个 java 程序,我需要读/写注册表。我已经查看了几个 API 来做到这一点,我发现了 ini4j(ini4j 项目页面)。我还需要编辑 ini 文件,所以我喜欢这个解决方案,因为它两者兼而有之。我很好奇是否有人在这种情况下尝试过 ini4j?
2 回答
我找到了一个更好的解决方案来读取/写入注册表,而无需使用 ini4j 或将参数传递给命令行。我在我的程序中经常使用 JNA,所以我认为使用本机库调用而不是包含一个额外的库来为我做这件事会更容易。这是我项目中的一个示例,我在注册表中搜索特定键。具体的密钥还取决于操作系统是 x64 还是 x86。
public static String GetUninstallerPath() {
try {
//if (logger.IsInfoEnabled) logger.Info("GetUninstallerPath - begin");
String uninstallerPath = null;
try {
String vncDisplayName = "UltraVNC";
String subkey32 = "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall";
String subkey64 = "Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall";
boolean is64Bit = Platform.is64Bit();
String[] key;
if (is64Bit) {
key = Advapi32Util.registryGetKeys(WinReg.HKEY_LOCAL_MACHINE,
subkey64);
} else {
key = Advapi32Util.registryGetKeys(WinReg.HKEY_LOCAL_MACHINE,
subkey32);
}
if (key != null) {
for (String nextSubkeyName : key) {
TreeMap<String, Object> subKey = Advapi32Util.registryGetValues(
WinReg.HKEY_LOCAL_MACHINE,
subkey64 + "\\" + nextSubkeyName);
Object value = subKey.get("DisplayName");
Object path = null;
if (value != null) {
if (value.toString().startsWith(vncDisplayName)) {
path = subKey.get("UninstallString");
if (path != null) {
uninstallerPath = path.toString().trim();
}
}
}
}
}
}
catch (Exception ex) {
System.err.println(ex.getMessage());
}
return uninstallerPath;
}
}
我使用对象来最初存储键值,因为我不断收到 NullPointerExceptions。随意提供另一种解决方案。
不幸的是,您使用 Platform.is64Bit() 对 64 位的测试并没有按照您的想法进行...
它会告诉您您的 JVM 是 32 位还是 64 位,而不是您的 Windows 是 32 位还是 64 位...
您的代码似乎按预期工作的唯一原因是因为 Windows 注册表重定向器为您处理了所涉及的“魔术”(访问正确的注册表项)......
当您的代码在 64 位 Windows Platform.is64Bit() 上的 32 位 JVM 上运行时,您正在使用 subkey32(即“Software\Microsoft\Windows\CurrentVersion\Uninstall”)。
不幸的是,我犯了与您相同的错误,并在阅读了诸如您的线程之类的线程后发布了具有相同错误测试的程序,这就是即使该线程已有几年历史,我现在仍发布此消息的原因。