我如何使用org.osgi.service.prefs.Preferences.clear()

时间:2013-02-06 00:01:10

标签: java eclipse osgi

我正在尝试使用org.osgi.service.prefs.Preferences加载并保存一些简单的偏好设置。第一次保存工作,但我在后续运行中所做的更改无法更改文件。查看APIa Vogella article,我认为我正在采取正确的步骤。当我在调试模式下运行时,在我调用clear()之后,我仍然看到相同的子键/值对。此外,在刷新首选项后,磁盘上的文件不会更改。我是否必须致电flush()才能使这项工作成功? (看起来很愚蠢,我应该刷新到磁盘来改变内存中的东西 - 而且它没有帮助)。

我做错了什么?

这是我保存描述符的代码(请注意,这是由McCaffer,Lemieux和Aniszczyk从“Eclipse Rich Client Platform”无耻地复制的,只需稍加修改即可更新Eclipse 3.8.1的API):

Preferences preferences = ConfigurationScope.INSTANCE.getNode(Application.PLUGIN_ID);
preferences.put(LAST_USER, connectionDetails.getUserId());
Preferences connections = preferences.node(SAVED);
try {
    connections.clear();
    //preferences.flush();
} catch (BackingStoreException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
preferences = ConfigurationScope.INSTANCE.getNode(Application.PLUGIN_ID);
connections = preferences.node(SAVED);
for (Iterator<String> it = savedDetails.keySet().iterator(); it.hasNext();) {
    String name = it.next();
    ConnectionDetails d = (ConnectionDetails) savedDetails.get(name);
    Preferences connection = connections.node(name);
    connection.put(SERVER, d.getServer());
    connection.put(PASSWORD, d.getPassword());
}
try {
    preferences.flush();
} catch (BackingStoreException e) {
    e.printStackTrace();
}       

1 个答案:

答案 0 :(得分:2)

必须刷新首选项才能正确应用修改,即您必须调用flush()。某些操作可能会自动刷新,但这是您不应该依赖的实现细节。此外,clear()仅删除所选节点上的键。要删除节点及其所有子节点,必须调用removeNode()

// get node "config/plugin.id"
// note: "config" identifies the configuration scope used here
final Preferences preferences = ConfigurationScope.INSTANCE.getNode("plugin.id");

// set key "a" on node "config/plugin.id"
preferences.put("a", "value");

// get node "config/plugin.id/node1"
final Preferences connections = preferences.node("node1");

// remove all keys from node "config/plugin.id/node1"
// note: this really on removed keys on the selected node
connections.clear();

// these calls are bogous and not necessary
// they get the same nodes as above
//preferences = ConfigurationScope.INSTANCE.getNode("plugin.id");
//connections = preferences.node("node1");

// store some values to separate child nodes of "config/plugin.id/node1"
for (Entry<String, ConnectionDetails> e : valuesToSave.entrySet()) {
    String name = e.getKey();
    ConnectionDetails d = e.getValue();
    // get node "config/plugin.id/node1/<name>"
    Preferences connection = connections.node(name);
    // set keys "b" and "c"
    connection.put("b", d.getServer());
    connection.put("c", d.getPassword());
}

// flush changes to disk (if not already happend)
// note: this is required to make sure modifications are persisted
// flush always needs to be called after making modifications
preferences.flush();