0

我正在尝试使用org.osgi.service.prefs.Preferences. 第一次保存有效,但我在后续运行中所做的更改无法更改文件。查看APIVogella 文章,我认为我正在采取正确的步骤。当我在调试模式下运行时,在我调用 之后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();
}       
4

1 回答 1

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();
于 2013-02-06T08:40:02.493 回答