Common Java Cookbook

Edition: 0.19

Download PDF or Read on Scribd

Download Examples (ZIP)

7.6. Configuring Applications with Properties Files

7.6.1. Problem

You need to access configuration parameters as typed objects. In other words, you have configuration parameters that may be numbers or lists of strings, and you want to access them as typed objects instead of first retrieving them as String objects from a Properties object.

7.6.2. Solution

Use the PropertiesConfiguration from Commons Configuration in the org.apache.commons.configuration package. This class loads a properties file and provides access to numbers, arrays, and lists. The following properties file contains three properties: speed is a floating-point number, names is a comma-separated list of strings, and correct is a boolean value:

speed=23.332
names=Bob,Gautam,Jarret,Stefan
correct=false

This properties file is stored in test.properties in the working directory of an application, which needs access to all three properties as a float, List, and boolean. The following code creates a PropertiesConfiguration and accesses each property:

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.PropertiesConfiguration;
Configuration config = new PropertiesConfiguration( "test.properties" );
        
float speed = config.getFloat("speed"));
List names = config.getList("names"));
boolean correct = config.getBoolean("correct");

7.6.3. Discussion

Passing a String to the constructor of PropertiesConfiguration will load configuration properties from a file named test.properties. Properties are then referenced by the key of the property in the properties file. This recipe demonstrates a modest improvement upon the existing Properties class that ships with the J2SE. The methods provided by the Configuration interface enable you to retrieve properties with a specific type, throwing a NumberFormatException, ClassCastException, and NoSuchElementException if there is a problem finding or parsing a property value.

7.6.4. See Also

For a full list of the methods provided by the Configuration interface, see the Commons Configuration JavaDoc at http://commons.apache.org/configuration/apidocs.


Creative Commons License
Common Java Cookbook by Tim O'Brien is licensed under a Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 United States License.
Permissions beyond the scope of this license may be available at http://www.discursive.com/books/cjcook/reference/jakartackbk-PREFACE-1.html. Copyright 2009. Common Java Cookbook Chunked HTML Output. Some Rights Reserved.