Introduction
Preferences (Java.util.pref) API is included in JDK can be used to remember and retrieve application preferences. Using this API you can manage preference data such as storing, retrieving, removing and cleaning preference data. This API is not intended to save application data. Also it reduces the burden of application developer to write the code to save the configuration values on different platforms.
Preferences in java are key-value pair. Preference works same as properties but they are persistent unlike Properties. Properties expects key-value pair as String but preferences has Key as String and Values can be of any primitive type like boolean, int, string. In background, when you write the preference it gets stored to a backing store and when you read a preference it load the value from the backing store.
Using the java.util.pref API
You can use the get()
method to retrieve value associated with a key from preference node and the put()
method to store a value associated with a key in the preference node. To remove a value associated with a key from preference node you can use the remove()
method. And if you want to clear the keys from the preference node you can use the clear()
method.
/****************************************************************************************
* Created on Oct 15, 2013 Copyright(c) https://kodehelp.com All Rights Reserved.
****************************************************************************************/
package com.kodehelp.java.util.pref;
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;
/**
* @author https://kodehelp.com
*
*/
public class PreferencesExample {
private Preferences pref;
public void setPreferences(){
//define a node to store preference data
pref = Preferences.userRoot().node(getClass().getName());
String KEY1 = "Key1";
String KEY2 = "Key2";
String KEY3 = "Key3";
//Reading the values of Key1, return empty string if the value is not set before.
System.out.println("VALUE1 = "+pref.get(KEY1, "null"));
// Reading value of Key2, returns int value 1 if the value is not set before.
System.out.println("VALUE2 = "+pref.getInt(KEY2, 1));
// Reading value of Key3, returns boolean value true if the value is not set before.
System.out.println("VALUE3 = "+pref.getBoolean(KEY3, true));
// Now we will set the values for above Keys. Above it returns
// default value if nothing is set before getting.
pref.put(KEY1, "Kodehelp");
pref.putInt(KEY2, 17);
pref.putBoolean(KEY3, false);
//removing preference for Key1
pref.remove(KEY1);
//removing all preferences from this node store
try {
pref.clear();
} catch (BackingStoreException e) {
e.printStackTrace();
}
}
/**
* @param args
*/
public static void main(String[] args) {
PreferencesExample preferencesExample = new PreferencesExample();
preferencesExample.setPreferences();
}
}
Output
VALUE1 = null
VALUE2 = 1
VALUE3 = true