Java Reference
In-Depth Information
Preferences
The
Preferences
class
java.util.prefs.Preferences
provides an easy-to-use mechan-
ism for storing user customizations in a system-dependent way (which might mean dot files
on Unix, a preferences file on the Mac, or the registry on Windows systems). This class
provides a hierarchical set of nodes representing a user's preferences. Data is stored in the
system-dependent storage format but can also be exported to or imported from an XML
format. Here is a simple demonstration of
Preferences
:
public
public class
class
PrefsDemo
PrefsDemo
{
public
public static
static
void
void
main
(
String
[]
args
)
throws
throws
Exception
{
// Setup the Preferences for this application, by class.
Preferences prefs
=
Preferences
.
userNodeForPackage
(
PrefsDemo
.
class
);
// Retrieve some preferences previously stored, with defaults in case
// this is the first run.
String text
=
prefs
.
get
(
"textFontName"
,
"lucida-bright"
);
String display
=
prefs
.
get
(
"displayFontName"
,
"lucida-blackletter"
);
System
.
out
.
println
(
text
);
System
.
out
.
println
(
display
);
// Assume the user chose new preference values: Store them back.
prefs
.
put
(
"textFontName"
,
"times-roman"
);
prefs
.
put
(
"displayFontName"
,
"helvetica"
);
// Toss in a couple more values for the curious who want to look
// at how Preferences values are actually stored.
Preferences child
=
prefs
.
node
(
"a/b"
);
child
.
putInt
(
"meaning"
,
42
);
child
.
putDouble
(
"pi"
,
Math
.
PI
);
// And dump the subtree from our first node on down, in XML.
prefs
.
exportSubtree
(
System
.
out
);
}
}
When you run the
PrefsDemo
program the first time, of course, it doesn't find any settings,
so the calls to
preferences.get( )
return the default values: