1

如何使用 Java 编写系统首选项Preferences.systemRoot()

我试过:

Preferences preferences = Preferences.systemRoot();
preferences.put("/myapplication/databasepath", pathToDatabase);

但我收到了这个错误信息:

2010-maj-29 19:02:50 java.util.prefs.WindowsPreferences openKey
VARNING: Could not open windows registry node Software\JavaSoft\Prefs at root 0x80000002. Windows RegOpenKey(...) returned error code 5.
Exception in thread "AWT-EventQueue-0" java.lang.SecurityException: Could not open windows registry node Software\JavaSoft\Prefs at root 0x80000002: Access denied
    at java.util.prefs.WindowsPreferences.openKey(Unknown Source)
    at java.util.prefs.WindowsPreferences.openKey(Unknown Source)
    at java.util.prefs.WindowsPreferences.openKey(Unknown Source)
    at java.util.prefs.WindowsPreferences.putSpi(Unknown Source)
    at java.util.prefs.AbstractPreferences.put(Unknown Source)
    at org.example.install.Setup$2.actionPerformed(Setup.java:43)

我想这样做,因为我想安装一个嵌入式 JavaDB 数据库,并让计算机上的多个用户在应用程序中使用同一个数据库。

如何解决这个问题?我可以调用 UAC 并以 Java 管理员身份执行此操作吗?如果我在写入时以管理员身份登录,如果我以用户身份登录,我可以使用我的 Java 应用程序读取这些值吗?

4

3 回答 3

2

您不能从 java 首选项写入任意注册表位置 - 所有首选项都存储在子项下Software\Javasoft\Prefs。将用户首选项映射到 HKEY_CURRENT_USER 配置单元,并将系统映射到HKEY_LOCAL_MACHINE配置单元。

要写入注册表,您可以使用 Windows 的“REG”命令行工具。此页面详细介绍了修改注册表的其他方法。包括.reg文件的使用。

我有同样的需要——从 java 写入注册表——我通过编写一个小的 .NET 命令行实用程序来解决它。

Sun Windows JDK 附带了通用代码来写入注册表的任意部分(WindowsPreferences),但它不是公开的。本文介绍如何使用反射访问此类。

于 2010-05-29T17:31:13.553 回答
1

如果打开了用户帐户控制,您将无法编辑 Preferences.systemRoot()。似乎微软去打破了它。这里有一个解决方法,但这并不简单。

于 2011-05-09T15:30:44.140 回答
0

So I had this same issue, so I opened an issue with Oracle: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7043176

I was able to work around it myself, by writing a custom implementation of AbstractPreferences and a corresponding PreferencesFactory. What I did was on Windows have the system preferences write to the application data directory defined in the registry by: HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders\Common AppData

I used Runtime.getRuntime().exec("reg query \""+key+ "\" /v \""+value+"\"") to get that (works even with UAC turned on).

That evaluates to "C:\ProgramData" on Windows 7 and "C:\Documents and Settings\All Users\Application Data" on XP. I added a subdirectory called "JavaPreferences" and wrote an implementation that uses a properties file as the backend.

As a side note, I had a similar issue with system preferences on Linux because the installer for the JRE was not run by root so I didn't have access to "/etc/.java". A ended up picking another custom directory and granting permissions for that.

于 2011-05-25T17:23:10.900 回答