Reading and Writing Configuration Properties

Java programs are more versatile when they can be configured using command-line arguments, as you have demonstrated in several apps created in preceding hours. The java.util package includes a class, Properties, that enables configuration settings to be loaded from a file. The file can be read like other file sources in Java:

  • Create a File object that represents the file
  • Create a FileInputStream object 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 equals sign ("=") and their values. Here's an example:

username=lepton lastCommand=open database windowSize=32


Each property has its own line, so this sets up properties named username, lastCommand, and windowSize with the values lepton, open database, and 32, respectively. The following code loads a properties file called config.dat:

File configFile = new File("config.dat");
FileInputStream configStream = new FileInputStream(configFile);
Properties config = new Properties();
config.load(configStream);


Configuration settings, which are called properties, are stored as strings in the Properties object. 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");
int windowSize = 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");


The altered properties can be stored back to the file:

  • Create a File object that represents the file
  • Create a FileOutputStream object from that File object
  • Call store() to save the properties to that output stream
      
Comments