java - 无法从 Java 将 boolean 首选项存储到 Windows 10 注册表,而整数和字符串可以正确存储

标签 java registry preferences

我正在使用 https://www.vogella.com/tutorials/JavaPreferences/article.html 中的示例使用以下代码:

import java.util.prefs.Preferences;

public class PreferenceTest {
  private Preferences prefs;

  public void setPreference() {
    // This will define a node in which the preferences can be stored
    prefs = Preferences.userRoot().node(this.getClass().getName());
    String ID1 = "Test1";
    String ID2 = "Test2";
    String ID3 = "Test3";

    // First we will get the values
    // Define a boolean value
    System.out.println(prefs.getBoolean(ID1, true));
    // Define a string with default "Hello World
    System.out.println(prefs.get(ID2, "Hello World"));
    // Define a integer with default 50
    System.out.println(prefs.getInt(ID3, 50));

    // now set the values
    prefs.putBoolean(ID1, false);
    prefs.put(ID2, "Hello Europa");
    prefs.putInt(ID3, 45);

    // Delete the preference settings for the first value
    prefs.remove(ID1);

  }

  public static void main(String[] args) {
    PreferenceTest test = new PreferenceTest();
    test.setPreference();
  }
}

下面是后续运行的输出:

1) 初始运行以保存首选项:

真实 2019 年 4 月 23 日 10:56:22 下午 java.util.prefs.WindowsPreferences Hello World 警告:无法在根 0x80000002 处打开/创建首选项根节点 Software\JavaSoft\Prefs。 Windows RegCreateKeyEx(...) 返回错误代码 5。 50

2) 第二次运行已读取第一次运行时写入的值:

真实 2019 年 4 月 23 日 10:56:57 下午 java.util.prefs.WindowsPreferences 你好欧罗巴 警告:无法在根 0x80000002 处打开/创建首选项根节点 Software\JavaSoft\Prefs。 Windows RegCreateKeyEx(...) 返回错误代码 5。 45

您可能会注意到,int 和 String 值都可以很好地检索,并且不会被默认值替换,而 boolean 值不会被检索并被替换为默认值(即,两个输出都给出 true,而期望为在第二次运行时实现 false)。

最佳答案

我错了:我错过了 ID1 key 已从首选项中删除的事实:

// Delete the preference settings for the first value
    prefs.remove(ID1);

如果我将其注释掉,一切都会按预期进行。

关于java - 无法从 Java 将 boolean 首选项存储到 Windows 10 注册表,而整数和字符串可以正确存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55818557/

相关文章:

java - 检查当前时间是午夜还是 Joda Time 的第二天?

java - 使用存储在外部文件中的值初始化变量

java - JPMS/Jigsaw 在模块中缺少主类

java - 以编程方式关闭当前显示的 Java Swing JDialog 框

c# - 如何以最简单的方式在 V 2010Express C# 中创建 MRU?

javascript - 如何让 Eclipse 在 Javascript 文档中做自动 javadoc 注释

windows - 如何让 Internet Explorer 正确处理自定义协议(protocol)处理程序?

Python win32api 注册表项更改

使用 java.util.prefs.Preferences 实现 Java 持久性

matlab - 如何让 Matlab 编辑器默认打开一个新脚本作为选项卡,而不是新窗口?