ptg7068951
292 HOUR 20: Reading and Writing Files
20:
21: output = output + newline;
22: byte[] data = output.getBytes();
23: stream.write(data, 0, data.length);
24: }
25:
26: public static void main(String[] arguments) {
27: ConfigWriter cw = new ConfigWriter();
28: }
29: }
When this application is run, it creates a file called program.properties
that contains the following three lines of text:
Output▼
username=max
score=12550
level=5
Reading and Writing Configuration
Properties
Java programs are more versatilewhen they can be configured using com-
mand-line arguments, as you have demonstrated in several applications
created in preceding hours. The java.utilpackage includes a class,
Properties, that enables configuration settings to be loaded from another
source: a text file.
The file can be read like other file sources in Java:
. Create a Fileobject that represents the file.
. Create a FileInputStreamobject from that File object.
. Call load()to retrieve the properties from that input stream.
A properties file has a set of property names followed by an equal sign (=)
and their values. Here’s an example:
username=lepton
lastCommand=open database
windowSize= 32
LISTING 20.3 Continued