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.

PreferenceTest.java

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"));
        storage.remove("Vendors");
        System.out.println(storage.get("Vendors", "No-Vendors"));
        storage = storage.node("/Vendors");
        storage.put("G", "Google");
        storage.put("Y", "Yahoo");
        storage.exportNode(System.out);
    }
}

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 "http://java.sun.com/dtd/preferences.dtd">
<preferences EXTERNAL_XML_VERSION="1.0">
    <root type="system">
        <map/>
            <node name="Vendors">
            <map>
                <entry key="G" value="Google"/>
                <entry key="Y" value="Yahoo"/>
            </map>
        </node>
    </root>
</preferences>

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*