无法从Java将布尔首选项存储到Windows 10注册表,而正确存储整数和字符串

问题描述 投票:0回答:1

我正在使用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)初始运行以保存首选项:

真的是Hello World,警告:无法在根0x80000002处打开/创建prefs根节点Software \ JavaSoft \ Prefs。 Windows RegCreateKeyEx(...)返回错误代码5. 50

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

真的是4月23日,2019 10:56:57 PM java.util.prefs.WindowsPreferences Hello Europa警告:无法在根0x80000002打开/创建prefs根节点Software \ JavaSoft \ Prefs。 Windows RegCreateKeyEx(...)返回错误代码5. 45

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

java registry preferences
1个回答
0
投票

我在这里错了:我错过了从首选项中删除ID1键的事实:

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

如果我发表评论,一切都按预期工作。

© www.soinside.com 2019 - 2024. All rights reserved.