Storing Application Data using Preferences API

Applications can now make use of the Java Preferences API for storing and retrieving Application related data. The location where the Data gets stored is implementation specific. Two levels of Preferences come into picture, one is the User Preferences for storing user information and the other is the System Preferences that deals with information common to all users as well as configuration details.

also read:

Let us see how to make use of this Preference API to deal with things. Consider the following program that puts up a simple data in the Preference Registry.

Preferences storage =  Preferences.systemRoot();
storage.put("Vendors", "Vendors");

The call to Preferences.systemRoot() will return the System Preferences Object for a particular implementation. And to store a simple string object, a call to Preferences.put(key, strValue) is enough. Similarly there are variants for adding other data-types like; Preferences.putBoolean(key, booleanValue), putDouble(key, doubleValue), putInt(key, intValue), putLong(key, longValue). To access the root node of the storage, simply use of the expression '/'. Subsequent node elements can be accessed using the expression '/ + {Name of the Node}'. For example to get a reference to the Vendors node, use '/Vendors'.

The following program makes use of the API to perform storage and retrieval operations.

package tips.pref;
import java.util.prefs.Preferences;
public class PreferenceTest {
    public static void main(String[] args) throws Exception {
        Preferences storage =  Preferences.systemRoot();
        storage.put("Vendors", "Vendors");
        System.out.println(storage.get("Vendors", "No-Vendors"));
        System.out.println(storage.get("Vendors", "No-Vendors"));
        storage = storage.node("/Vendors");
        storage.put("G", "Google");
        storage.put("Y", "Yahoo");

Note that the code finally exports the content of the entire storage by making a call to Preferences.exportNode(). This will export the storage contents to an Output stream in Xml format. Given below is the content of the storage in Xml format,

<?xml version="1.0" encoding="UTF-8&quot; standalone="no"?>
<!DOCTYPE preferences SYSTEM "">
<preferences EXTERNAL_XML_VERSION="1.0">
    <root type="system">
            <node name="Vendors">
                <entry key="G" value="Google"/>
                <entry key="Y" value="Yahoo"/>

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest

Share This

Share this post with your friends!