Java Reference
In-Depth Information
To store a preferences item takes one more line of code - the
prefs.put()
method. To retrieve a stored item at a later time, say the next time the application
is run, takes just one line of code - the
prefs.get()
method.
Preferences information is stored as key/value pairs by the
Preferences
object, similar to the way system properties are stored, so the call to the
put()
method must provide both the name of the key under which the item is to be
stored and its value, both as
String
objects. An example is
prefs.put (
"
color
"
,
"
red
"
);
Here the key
“color
„
is stored with the value
“red
„
.You choose the key names
to be whatever makes sense. Then, the next time the same Java application is run
by the same user, the previously stored value can be retrieved with
String preferred
-
color
=
prefs.get (
"
color
"
,
"
some-default-value
"
);
All of the preferences methods that retrieve values require a second parameter
that provides a default value in case nothing is found under the named key. In that
way, the application can continue running with default values, although perhaps
with slightly reduced functionality.
In addition to the general
put()
and
get()
methods described above, there
are convenience methods to store and retrieve
int
values:
prefs.putInt ("width", 500);
int preferred
-
width = prefs.get ("width", 700);
Here, the integer value 500 is stored under the key name
width
. Later the value
stored is retrieved and loaded into the
int
variable
preferred
-
width
, using
a default value of 700. There are similar convenience methods for
boolean
(
putBoolean()
and
getBoolean()
),
long
(
putLong()
and
getLong()
),
float
(
putFloat()
and
getFloat()
), and
double
(
putDouble()
and
getDouble()
)values. There are even convenience methods to put and get
abyte array. Another useful method is
clear()
,which removes all key/value
pairs in the preferences node.
10.5.2 Working examples
The Web Course Chapter 10 includes an example of the Preferences API usage
in a simple command-line Java application. The
PrefsDemo
application stores
values under the key name
“PrefsValue
„
. The simple application is set up
to accept either “put”, “get”, or “clear” on the command line. These command
line parameters may put the next value supplied on the command line into the
preferences node, or they may get and echo a previously stored value or clear
Search WWH ::
Custom Search