7.6. Configuring Applications with Properties Files
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.
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");Discussion
Passing a String to the constructor of
PropertiesConfiguration will load configuration
properties from a file named test.properties. Properties are then referenced by ...
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