Category Archives: Preferences

Useful Java Snippets (4)

ejwagenaar.com logo

Hello all of you Java geeks!

Welcome back to a new episode of this fine Java snippet series! In former episodes we looked at the  java.util package. We covered the Collections Framework as well as utilities to convert between Collections, Arrays and back to Collections again. We also covered Locales to make your Applications International.

Time to move on to another part of the java.util area. Today I choose  the java.util.prefs also known as the Java Preferences API.

This package allows applications to store and retrieve user and system preference and configuration data. This data is stored persistently in an implementation-dependent backing store. There are two separate trees of preference nodes, one for user preferences and one for system preferences.

The Java Preferences API provides a systematic way to handle program preference configurations, e.g. to save user settings, remember the last value of a field etc.

Preferences are key / values pairs where the key is an arbitrary name for the preference. The value can be a boolean, string, int of another primitive type. Preferences are received and saved by get and put methods while the get methods also supply a default value in case the preferences is not yet set.

Format

Preferences in Java are readable text documents, either the Properties format or XML variants thereof. You don’t have to worry to much about that yet. Eclipse or your preferred IDE can help you with this and you only use accessor methods (getters and setters) to work with them.

Your Java Runtime Environment (JRE) has it’s own set of preferences.

1. Listing your JRE Preferences

// Get all system properties
Properties props = System.getProperties();

// Enumerate all system properties
Enumeration enum = props.propertyNames();
for (; enum.hasMoreElements(); ) {
    // Get property name
    String propName = (String)enum.nextElement();

    // Get property value
    String propValue = (String)props.get(propName);
}
  1. Getting and setting values in preferences:

A preference node holds only string values. However, the Preferences class has convenience methods that will convert a number of basic Java types to and from strings. For example, Preferences.putByteArray() converts a byte array into a string and then saves the string value. Preferences.getByteArray() converts the string back into an array of bytes.
The types for which there are conversion methods are boolean, int, long, float, double, and byte[]. For all other types, serialization can be used to convert an arbitrary Java type into a byte array (see Serializing an Object).

// Retrieve the user preference node for the package com.mycompany
Preferences prefs = Preferences.userNodeForPackage(com.mycompany.MyClass.class);

// Preference key name
final String PREF_NAME = "name_of_preference";

// Save
prefs.put(PREF_NAME, "a string"); // String
prefs.putBoolean(PREF_NAME, true); // boolean
prefs.putInt(PREF_NAME, 123); // int
prefs.putLong(PREF_NAME, 123L); // long
prefs.putFloat(PREF_NAME, 12.3F); // float
prefs.putDouble(PREF_NAME, 12.3); // double
byte[] bytes = new byte[1024];
prefs.putByteArray(PREF_NAME, bytes); // byte[]

// Retrieve
String s = prefs.get(PREF_NAME, "a string"); // String
boolean b = prefs.getBoolean(PREF_NAME, true); // boolean
int i = prefs.getInt(PREF_NAME, 123); // int
long l = prefs.getLong(PREF_NAME, 123L); // long
float f = prefs.getFloat(PREF_NAME, 12.3F); // float
double d = prefs.getDouble(PREF_NAME, 12.3); // double
bytes = prefs.getByteArray(PREF_NAME, bytes); // byte[]
  1. Serializing an Object:

The types for which there are conversion methods are boolean, int, long, float, double, and byte[]. For all other types, serialization can be used to convert an arbitrary Java type into a byte array and can be serialized as follows:

Note: The Object to be Serialized must implement java.io.Serializable.

This example serializes a javax.swing.JButton object.

Object obj = new javax.swing.JButton("push me");

try {
    // Serialize to a file
    ObjectOutput out = new ObjectOutputStream(new FileOutputStream("filename.ser"));
    out.writeObject(object);
    out.close();

    // Serialize to a byte array
    ByteArrayOutputStream bos = new ByteArrayOutputStream() ;
    out = new ObjectOutputStream(bos) ;
    out.writeObject(object);
    out.close();

    // Get the bytes of the serialized object
    byte[] buf = bos.toByteArray();
} catch (IOException e) {
}

Off course now we serialized our JButton we also need to bring it back to the original JButton Object. This is called Deserialization. You do it as follows:

try {
    // Deserialize from a file
    File file = new File("filename.ser");
    ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
    // Deserialize the object
    javax.swing.JButton button = (javax.swing.JButton) in.readObject();
    in.close();

    // Get some byte array data
    byte[] bytes = getBytesFromFile(file);
    // see Reading a File into a Byte Array for the implementation of this method

    // Deserialize from a byte array
    in = new ObjectInputStream(new ByteArrayInputStream(bytes));
    button = (javax.swing.JButton) in.readObject();
    in.close();
} catch (ClassNotFoundException e) {
} catch (IOException e) {
}
  1. Saving and Retrieving a Preference Value

Preference values are persistent key/value pairs. The key must be a string. Preference values are stored in a preference node, which behaves much like a Map object. In order to get or set a preference value, the preference node containing that preference must first be retrieved.
By convention, a preference node is associated with a Java package. For example, if a class called com.mycompany.Foo needs to save some preferences, it would save them in the preference node associated with the package com.mycompany.

There are two types of preference nodes: a system type and a user type. A system node is shared by all users of a system. Any changes made to a system node are immediately visible to all users of the system. A user node is a node whose values are accessible only by the user using the application.

A preference node can be retrieved using a Class object or by a string. See Retrieving a Preference Node for an example.

This example retrieves the user preference node using a Class object and saves and retrieves a preference in the node.

// Retrieve the user preference node for the package com.mycompany
Preferences prefs = Preferences.userNodeForPackage(com.mycompany.MyClass.class);

// Preference key name
final String PREF_NAME = "name_of_preference";

// Set the value of the preference
String newValue = "a string";
prefs.put(PREF_NAME, newValue);

// Get the value of the preference;
// default value is returned if the preference does not exist
String defaultValue = "default string";
String propertyValue = prefs.get(PREF_NAME, defaultValue); // "a string"

Enough for today chaps! Hope you can ingest this all. I need to do some coding myself.