Java Reference
In-Depth Information
all key/value pairs. Because we always provide a default value when attempt-
ing to retrieve stored preferences, as is required, any attempt to retrieve a value
before one is stored results in a suitable default value being returned. You may
download and compile the PrefsDemo application and play with the “put”,
“get”, and “clear” parameters to get a feel for how the Preferences API works. In
addition to the “PrefsValue key name, the demo also uses the putInt()
and getInt() convenience methods to keep track of the total number of “put”
operations that have been performed. This counter is incremented by one each
time a “put” is performed and, more importantly, the value is maintained across
application invocations, even across recompilations and reboots! If the first com-
mand line parameter is “clear”, then all key/value pairs are removed from the
preferences node, effectively resetting the counter back to 0.
10.5.3 Exporting and importing preferences
Okay, we've shown that it's easy to store and retrieve preferences. Doing so, and
having it work with so little effort, is almost magical - as long as your application
always runs on the same machine. But what about moving to another machine?
How can we not lose the preferences already stored on the first machine? The
answer is to use the export and import facilities of the Preferences API. The
exportNode() method creates an XML document (see a discussion of XML
in Chapter 21) on the specified OutputStream that can then be transferred and
imported to the same application running on another machine. Because of the
cross-platform nature of XML, the preferences XML file can even be moved to
the same Java application running on a completely different platform.
If the last parameter to the javatech.prefs.PrefsDemo application is
“export”, then the app uses exportNode() to output the preferences XML file
onto System.out. In this way, you can examine the tree and node structure of
the preferences tree.
Use of the importPreferences() method to read in an XML preferences
file is not shown in the demo application, but its use is straightforward after
referring to the online documentation.
10.5.4 System preferences
So far we've talked about user-level preferences - i.e. preferences stored for a
particular user. The Preferences API also supports system-level preferences that
apply to all users. To reach the system-wide portion of the preferences storage
system, use
Preferences prefs = Preferences.systemNodeForPackage
(getClass ());
Search WWH ::




Custom Search