Get started with the Java Preferences API

The Preferences API, introduced in JDK1.4, allows you to save and retrieve user and system configuration data. What you typically would do before was to save this configuration data in an XML, INI or Properties file in a specified directory known to your application. When you use the preferences API, you don’t care where this data is located. On a Windows machine, it’ll be saved in the registry, even though it is subject to change in future releases. On linux, files will be used to save your preferences (/etc/.java/.systemPrefs for system preferences and USERHOME/.java/.userPrefs for user preferences).

The Preferences API is very simple to use. Instantiate a Preferences object and use the method put to save a key, value pair. With get you can retrieve the values, even with another VM. The API uses the packagename to differentiate between preferences of different applications.

Here’s an example where you can set some preferences. When it starts up, it fills up the fields according to their values in the backing store.

comesusexamplespreferencesMain.java:

package com.esus.examples.preferences;
 
import javax.swing.border.*;
import java.util.prefs.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame 
{
   Preferences preferences;
 
   public static final String APPLICATIONPATH = "applicationpath";
   public static final String USERFONT        = "userfont";
   public static final String LASTUSERLOGIN   = "lastuserlogin";
   public static final String LDAPURL         = "ldapurl";
 
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
 
      loadPreferences();
 
      JLabel appPathLabel       = new JLabel("Application Path:");
      JLabel userFontLabel      = new JLabel("User font:");
      JLabel lastUserLoginLabel = new JLabel("Last user logged in: ");
      JLabel ldapURLLabel       = new JLabel("LDAP url:");
      final JTextField appPathTf       = new JTextField(
                                  preferences.get(APPLICATIONPATH, ""));
      final JTextField userFontTf      = new JTextField(
                                  preferences.get(USERFONT, ""));
      final JTextField lastUserLoginTf = new JTextField(
                                  preferences.get(LASTUSERLOGIN, ""));
      final JTextField ldapURLTf       = new JTextField(
                                  preferences.get(LDAPURL, ""));
 
      JPanel prefsPanel = new JPanel();
      prefsPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
      prefsPanel.setLayout(new GridLayout(4, 4, 10, 10));
      prefsPanel.add(appPathLabel);
      prefsPanel.add(appPathTf);
      prefsPanel.add(userFontLabel);
      prefsPanel.add(userFontTf);
      prefsPanel.add(lastUserLoginLabel);
      prefsPanel.add(lastUserLoginTf);
      prefsPanel.add(ldapURLLabel);
      prefsPanel.add(ldapURLTf);
 
      JPanel buttonPanel = new JPanel();
      buttonPanel.setLayout(new GridLayout(1, 2, 70, 70));
 
      JButton cancelButton = new JButton("Cancel");
      cancelButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            System.exit(0);
         }
      });
 
      JButton saveButton = new JButton("Save");
      saveButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            try {
               preferences.put(APPLICATIONPATH, appPathTf.getText());
               preferences.put(USERFONT,        userFontTf.getText());
               preferences.put(LASTUSERLOGIN,   lastUserLoginTf.getText());
               preferences.put(LDAPURL,         ldapURLTf.getText());
 
               // ensure all data is flushed to the backing store
               preferences.flush();
 
               System.out.println("Preferences saved!");
            }
            catch(BackingStoreException e) {
               e.printStackTrace();
            }
         }
      });
 
      buttonPanel.add(cancelButton);
      buttonPanel.add(saveButton);
 
      getContentPane().setLayout(new BorderLayout());
      getContentPane().add(BorderLayout.CENTER, prefsPanel);
      getContentPane().add(BorderLayout.SOUTH, buttonPanel);
   }
 
   public void loadPreferences() {
      preferences = Preferences.userNodeForPackage(this.getClass());
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(350, 190);
      main.setVisible(true);
   }
}

Take a look at the Windows registry in the key \HKEY_CURRENT_USERSOFTWAREJavaSoftPrefs

.

If you want to load these preferences from another application, specify the node.

Main2.java:

import java.util.prefs.*;
 
public class Main2
{
   public static final String APPLICATIONPATH = "applicationpath";
   public static final String USERFONT        = "userfont";
   public static final String LASTUSERLOGIN   = "lastuserlogin";
   public static final String LDAPURL         = "ldapurl";
 
   public static void main(String []args) {
      String nodename = "/com/esus/examples/preferences";
 
      Preferences preferences = Preferences.userRoot().node(nodename);
      System.out.println(preferences.get(APPLICATIONPATH, ""));
      System.out.println(preferences.get(USERFONT, ""));
      System.out.println(preferences.get(LASTUSERLOGIN, ""));
      System.out.println(preferences.get(LDAPURL, ""));
   }
}

outputs:

c:application
Courier New
Joris Van den Bogaert
ldap://localhost:389

Notice also that by using userRoot you are working with preferences for that user. You can also work with system preferences (shared by all users) by specifying systemRoot.

When you perform a get, you have 2 parameters: one for the key and one for the default value. Whenever the value is not available on the backing store, the default value will be returned, if specified.

In the following example, PORT is not available on the backing store.

Main3.java:

import java.util.prefs.*;
 
public class Main3
{
   public static final String APPLICATIONPATH = "applicationpath";
   public static final String USERFONT        = "userfont";
   public static final String LASTUSERLOGIN   = "lastuserlogin";
   public static final String LDAPURL         = "ldapurl";
   public static final String PORT            = "port";
 
   public static final String DEFAULTPORT     = "2506";
 
   public static void main(String []args) {
      String nodename = "/com/esus/examples/preferences";
 
      Preferences preferences = Preferences.userRoot().node(nodename);
      System.out.println(preferences.get(APPLICATIONPATH, ""));
      System.out.println(preferences.get(USERFONT, ""));
      System.out.println(preferences.get(LASTUSERLOGIN, ""));
      System.out.println(preferences.get(LDAPURL, ""));
 
      System.out.println(preferences.get(PORT, DEFAULTPORT));
   }
}

outputs:

c:application
Courier New
Joris Van den Bogaert
ldap://localhost:389
2506