Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

Reading and Writing Configuration Properties 293

Each property has its own line, so this sets up properties named username,
lastCommand, and windowSizewith the values “lepton”, “open database”,
and “32”, respectively. (The same format was used by the ConfigWriter
class.)


The following code loads a properties file called config.dat:


File configFile = new File(“config.dat”);
FileInputStream inStream = new FileInputStream(configFile);
Properties config = new Properties();
config.load(inStream);


Configuration settings, which are called properties, are stored as strings in
the Propertiesobject. Each property is identified by a key that’s like an
applet parameter. The getProperty()method retrieves a property using
its key, as in this statement:


String username = config.getProperty(“username”);


Because properties are stored as strings, you must convert them in some
manner to use a numerical value, as in this code:


String windowProp = config.getProperty(“windowSize”);
intwindowSize = 24;
try {
windowSize = Integer.parseInt(windowProp);
} catch(NumberFormatException exception) {
// do nothing
}


Properties can be stored by calling the setProperty()method with two
arguments—the key and value:


config.setProperty(“username”, “max”);


You can display all properties by callingthe list(PrintStream)method of
the Propertiesobject. PrintStreamis the class of the outvariable of the
Systemclass, which you’ve been using throughout the book to display out-
put in System.out.println()statements. The following code calls list()
to display all properties:


config.list(System.out);


After you have made changes to the properties, you can store them back to
the file:


. Create a Fileobject that represents the file.
. Create a FileOutputStreamobject from that File object.

Free download pdf