Finding a Preference in a Preference Tree - Java Native OS

Java examples for Native OS:Preference

Description

Finding a Preference in a Preference Tree

Demo Code


import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;

public class Main {
  public static void main(String[] args) throws Exception {
    // 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");
    }//from w w w  .  j av a2s .co m
  }
  static boolean contains(Preferences root, String key){
    return false;
  }
  public static Preferences findNode(Preferences root, Preferences start,
      String key) {
    if (start == null && contains(root, key)) {
      // Found the key
      return root;
    }

    if (start != null && root.equals(start)) {
      start = null;
    }

    // Recursively check the child nodes
    try {
      String[] names = root.childrenNames();
      for (int i = 0; i < names.length; 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;
  }
}

Result


Related Tutorials