Properties
The java.util.Properties
class is a specialized hash table for strings. Properties are generally
used to hold textual configuration data. Examples of this are the Java
System properties, which are passed to a Java application on the command
line. We’ll cover those later in this section. More generally, you can use
a Properties table to hold arbitrary
configuration information for an application in an easily accessible
format. The neat thing about a Properties object is that it can load and store
its information in a plain text or XML text format using streams (see
Chapter 12 for information on streams).
Any string values can be stored as key/value pairs in a Properties table. However, the convention is to
use a dot-separated naming hierarchy to group property names into logical
structures. (Unfortunately, this is just a convention, and you can’t
really work with groups of properties in a hierarchical way as this might
imply.) For example, you can create an empty Properties object and add String key/value pairs just as you could with a
Map:
Propertiesprops=newProperties();props.setProperty("myApp.xsize","52");props.setProperty("myApp.ysize","79");
Thereafter, you can retrieve values with the getProperty()
method:
Stringxsize=props.getProperty("myApp.xsize");
If the named property doesn’t exist, getProperty() returns null. You can get an Enumeration of the property names with the
propertyNames()
method:
for(Enumeratione=props.propertyNames();e.hasMoreElements ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access