The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > java.util.prefs  [18 examples]

e405. Saving and Retrieving a Preference Value

Preference values are persistent key/value pairs. The key must be a string. Preference values are stored in a preference node, which behaves much like a Map object. In order to get or set a preference value, the preference node containing that preference must first be retrieved.

By convention, a preference node is associated with a Java package. For example, if a class called com.mycompany.Foo needs to save some preferences, it would save them in the preference node associated with the package com.mycompany.

There are two types of preference nodes: a system type and a user type. A system node is shared by all users of a system. Any changes made to a system node are immediately visible to all users of the system. A user node is a node whose values are accessible only by the user using the application.

A preference node can be retrieved using a Class object or by a string. See e413 Retrieving a Preference Node for an example.

This example retrieves the user preference node using a Class object and saves and retrieves a preference in the node.

    // Retrieve the user preference node for the package com.mycompany
    Preferences prefs = Preferences.userNodeForPackage(com.mycompany.MyClass.class);
    
    // Preference key name
    final String PREF_NAME = "name_of_preference";
    
    // Set the value of the preference
    String newValue = "a string";
    prefs.put(PREF_NAME, newValue);
    
    // Get the value of the preference;
    // default value is returned if the preference does not exist
    String defaultValue = "default string";
    String propertyValue = prefs.get(PREF_NAME, defaultValue); // "a string"

 Related Examples
e406. Determining If a Preference Node Contains a Specific Key
e407. Determining If a Preference Node Contains a Specific Value
e408. Removing a Preference from a Preference Node
e409. Getting and Setting Java Type Values in a Preference
e410. Getting the Maximum Size of a Preference Key and Value

See also: Events    Importing and Exporting    Nodes   


© 2002 Addison-Wesley.