There is no efficient method for finding a key in a preference node. All the nodes must be traversed and checked for the presence of the key. This example implements such a method.
This example can be modified to find nodes that matched values rather than keys by replacing contains() with containsValue(), as defined in e407 Determining If a Preference Node Contains a Specific Value.
// Find first occurrence
Preferences prefs = findNode(Preferences.userRoot(), null, "key");
// Find all occurrences
prefs = findNode(Preferences.userRoot(), null, "key");
while (prefs != null) {
prefs = findNode(Preferences.userRoot(), prefs, "key");
}
// Traverses all the nodes from root depth-first.
// Returns the first node that contains the specified key.
// If start is non-null, the nodes are checked only after the
// start node is encountered.
// Returns null if not found.
public static Preferences findNode(Preferences root, Preferences start, String key) {
// For the implementation of contains,
// see e406 Determining If a Preference Node Contains a Specific Key
if (start == null && contains(root, key)) {
// Found the key
return root;
}
// The start node has been encountered so start checking from now on
if (start != null && root.equals(start)) {
start = null;
}
// Recursively check the child nodes
try {
String[] names = root.childrenNames();
for (int i=0; i Preferences n = findNode(root.node(names[i]), start, key);
if (n != null) {
// Found the key
return n;
}
}
} catch (BackingStoreException e) {
}
// Not found
return null;
}
Related Examples