我正在尝试使用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();
}

最佳答案

必须清除首选项才能正确应用修改,即您必须调用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();

07-24 19:18
查看更多