Datasheet

Java Preferences
Programs commonly must store configuration information in some manner that is easy to change and
external to the program itself. Java offers utility classes for storing and retrieving system-defined and
user-defined configuration information. There are separate hierarchies for the user and system informa-
tion. All users share the preference information defined in the system tree; each user has his or her own
tree for configuration data isolated from other users. This allows for custom configuration, including
overriding system values.
The core of the preferences class library is the abstract class
java.util.prefs.Preferences. This
class defines a set of methods that provides for all the features of the preferences library.
Each node in a preference hierarchy has a name, which does not have to be unique. The root node of a
preference tree has the empty string (“”) as its name. The forward slash is used as a separator for the
names of preference nodes, much like it is used as a separator for directory names on Unix. The only two
strings that are not valid node names are the empty string (because it is reserved for the root node) and a
forward slash by itself (because it is a node separator). The root node’s path is the forward slash by itself.
Much like with directories, absolute and relative paths are possible. An absolute path always starts with
a forward slash, because the absolute path always starts at the root node and follows the tree down to a
specific node. A relative path never starts with a forward slash. A path is valid as long as there aren’t
two consecutive forward slashes in the pathname, and no path except the path to root ends in the for-
ward slash.
Because preferences are implemented by a third-party implementer, changes to the preferences aren’t
always immediately written to the backing store.
The maximum length of a single node’s name and any of its keys is 80 characters. The maximum length
of a string value in a node is 8,192 characters.
The Preferences Class
The Preferences class is the main class used for dealing with preferences. It represents a node in the
preference’s tree and contains a large number of methods to manipulate this tree and also nodes in the
tree. It is basically a one-stop shop for using preferences. The following sections outline the
Preferences methods.
Operations on the Preferences Tree
The Preferences class defines a number of methods that allow for the creation/deletion of nodes and
the retrieval of certain nodes in the tree.
Method Description
Preferences node(String pathName) Returns a specified node. If the node does
not exist, it is created (and any ancestors
that do not exist are created) and returned.
boolean nodeExists(String pathName) Returns true if the path to a node exists in
the current tree. The path can be an abso-
lute or relative path.
70
Part I: Thinking Like a Java Developer
05_777106 ch01.qxp 11/28/06 10:43 PM Page 70