Stop the key-value pair insanity
The Properties
class is an old favorite, around since the beginning
of Java programming time with very few changes. The Tiger release of
J2SE enhances this class, which allows you not only to use it to
specify key-value pairs on a single line separated by an equal sign,
but also to use XML files to load and save those key-value pairs. In
this installment of Taming Tiger,
John Zukowski demonstrates how to use this updated work horse. Share
your thoughts on this article with the author and other readers in the
accompanying discussion forum. (You can also click Discuss at the top or bottom of the article to access the forum.)
J2SE versions prior to 1.5 required you to work directly with the XML parser
to load a configuration file and store settings. While it was never
difficult, and while the parser is a standard part of the platform, the
extra work was a bit of an annoyance. The newly updated java.util.Properties
class now offers an easier way to load and store settings for a program: the loadFromXML(InputStream is)
and storeToXML(OutputStream os, String comment)
methods.
Properties basics
If you aren't familiar with the java.util.Properties
class, you use it to store a set of key-value pairs in a file, where
the key and value are separated by an equal sign, as shown in Listing 1.
|
Had Listing 1 been loaded into a Properties
object, you would then find two keys (foo
and fu
) and two values (bar
for foo
and baz
for fu
). The class supports embedding Unicode strings with \u
, but the important thing here is that everything is treated as a String
.
J2SE 1.5 Beta 1 now available |
Listing 2 shows how to load the properties file and list its current set of keys and values. You just pass an InputStream
for the file to the load()
method, and each key-value pair is added to the Properties
instance. You would then use list()
to list all the properties or getProperty()
to retrieve an individual one.
Listing 2. Loading properties
|
Running the LoadSample program produces the output in Listing 3. Notice that the output of the list()
method does not produce the list of key-value pairs in the same order they were in the input file. The Properties
class stores the set of pairs in a hashtable (in fact, it is a Hashtable
subclass), so there is no guarantee for order.
|
View Taming Tiger: Loading Properties from XML Discussion
Page: 1 2 3 4 Next Page: XML property files