Java Reference
In-Depth Information
The Preferences API is in the java.util.prefs package and has been a
part of Java since version 1.4. Amazingly, it provides the tools to easily store
and retrieve user preferences that persist across application invocations (i.e. the
preferences are “remembered” from one run of an application to the next). It
automatically maintains separate preference lists for multiple users, and trans-
parently handles storing the preferences information (the “configuration file,”
if you wish) in a way that the programmer need never worry about. The actual
place that the preferences data is stored is platform dependent ,but the Preferences
API transparently handles access to the preferences information in a platform-
independent manner. Put another way, source code that uses the Preferences API
behaves the same way on any platform and hides the fact that the preferences
data might be stored differently on different platforms. The API even includes
a platform-independent import/export facility so that preferences can be backed
up or moved from one machine to another.
10.5.1 Easy to use
The Preferences API is very easy to use, despite what you might think after a
first brush with the online API documentation [3]. The most important class in
java.util.prefs is the Preferences class. Alas, the online documen-
tation is not written in a tutorial manner. That documentation says that the
Preferences class is “a node in a hierarchical collection of preference data”
and continues later with “there are two separate trees of preference nodes, one
for user preferences and one for system preferences.” While nodes and trees may
not sound simple or easy to use, they really are, and we explain how to use the
Preferences API through a simple example.
One first obtains a Preferences object by using the static method
userNodeForPackage() . This method requires a Class object as its only
parameter. The system then determines the package in which the specified class
resides and returns the Preferences object to be used to access user prefer-
ences information for that package. Since all applications generally have their
own unique package names, preferences based on package names do not conflict
with other packages. The userNodeForPackage() method returns a differ-
ent Preferences object for each user. In that way, multiple users of the same
application on the same machine do not conflict with each other. That is, dif-
ferent users, as distinguished by different user.name system property values,
have separate storage locations for their preferences data.
The description so far may not sound simple and easy to use yet, but the
API really is simple, as the following code snippets illustrate. So far, we have
described one line of code to obtain the Preferences object:
Preferences prefs = Preferences.userNodeForPackage
(getClass ());
Search WWH ::




Custom Search