Reading and writing configuration/preference data is a trivial functionality of any software program. In Java programming, we can use the java.util.Properties class to store configuration data as key/value pairs in a .properties file (See: Reading and writing configuration for Java application using Properties class). However, using the Properties class requires the program has to manage location of the configuration file. In this tutorial, we introduce another approach using the java.util.prefs.Preferences class which stores and retrieves configuration data in an OS-specific way (such as registry entries on Windows OS). Using the Preferences class, we don’t have to care about the file location and how the data is stored, thus easier than using the Properties class.

1. Obtaining a Preferences node

In Java, each Preferences object represents a node in a tree of preference data, and there are two separate trees of preference nodes: user preferences and system preferences. Typically, the user preferences tree stores user-specific and program-specific configuration data and the system preferences tree stores global configuration data which is shared among users and programs.

Obtaining a System preferences node

The following code obtains a reference of system preferences node associated with the MyProgram class:

Preferences systemPrefs = Preferences.systemNodeForPackage(MyProgram.class);

 

If the MyProgram class resides under the package net.codejava.app, then the returned node will have path name of “/net/codejava/app”. If the node does not exist, it will be created.

We can obtain the root node of system preferences as follows:

Preferences rootSystemPrefs = Preferences.systemRoot();

 

The root node has path name of “/”.

Obtaining a user preferences node

The following code obtains a reference of user preferences node associated with the MyProgram class:

Preferences userPrefs = Preferences.userNodeForPackage(MyProgram.class);

 

We can obtain the root node of user preferences as follows:

Preferences rootUserPrefs = Preferences.userRoot(); 


2. Writing preference data

Now, with the reference of a preferences node, we can use the putXXX(key, value) methods to store configuration data. For example:

userPrefs.put("hostname", "www.codejava.net");	// put String value
userPrefs.putInt("port", 12345);
userPrefs.putBoolean("authentication", true);
userPrefs.putLong("timeout", 90000);

 

Calling putXXX() multiple times for a same key will overwrite the previous value.

We can even put a byte array, for example:

byte[] byteArray = ...
userPrefs.putByteArray("byteData", byteArray); 

 

 

3. Reading preference data

To retrieve configuration data from a preference node, use the getXXX(key, defaultValue) methods. For example:

String hostname = userPrefs.get("hostname", null);
int port = userPrefs.getInt("port", 80);
boolean authentication = userPrefs.getBoolean("authentication", false);
long timeout = userPrefs.getLong("timeout", 20000);

// this would return "tom" because the key "username" does not exist
String username = userPrefs.get("username", "tom");

 

We can also retrieve all keys of the current node and print their values as follows:

String[] keys = userPrefs.keys();
for (String key : keys) {
	System.out.println(key + " = " + userPrefs.get(key, null));
}


4. Removing preference data

When a key is no longer used, it can be removed from the preference node using the remove(key) method like this:

userPrefs.remove("hostname");

 

Or remove the complete preference node (including its children) like this:

userPrefs.removeNode(); 


5. A complete example program

The following program creates a user preference node, checks if there is no key exists, and then stores some configuration data. If there are keys, retrieves their values and prints out them to the console. Here’s the code:

package net.codejava.io;

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

/**
 * This program demonstrates how to use the Preferences class to store and
 * retrieve preference data.
 * @author www.codejava.net
 *
 */
public class PreferencesDemo {

	public static void main(String[] args) {
		Preferences userPrefs = Preferences.userNodeForPackage(PreferencesDemo.class);

		try {
			String[] keys = userPrefs.keys();
			
			if (keys == null || keys.length == 0) {
				userPrefs.put("hostname", "www.codejava.net");
				userPrefs.putInt("port", 12345);
				userPrefs.putBoolean("authentication", true);
				userPrefs.putLong("timeout", 90000);
			} else {
				String hostname = userPrefs.get("hostname", null);
				int port = userPrefs.getInt("port", 80);
				boolean authentication = userPrefs.getBoolean("authentication", false);
				long timeout = userPrefs.getLong("timeout", 20000);

				String username = userPrefs.get("username", "tom");
				
				System.out.println(hostname);
				System.out.println(port);
				System.out.println(authentication);
				System.out.println(timeout);
				System.out.println(username);
			}
		} catch (BackingStoreException ex) {
			System.err.println(ex);
		}
	}
}

 

You should run this program twice to see the effect.

Reference: java.util.prefs.Preferences Java doc

 

Recommended Book: Java I/O

Submit to DeliciousSubmit to DiggSubmit to FacebookSubmit to Google BookmarksSubmit to StumbleuponSubmit to TechnoratiSubmit to TwitterSubmit to LinkedIn
Attachments:
Download this file (PreferencesDemo.java)PreferencesDemo.java[Demo program]1 kB