The Lab Book Pages

An online collection of electronics information

http://www.labbookpages.co.uk

Dr. Andrew Greensted
Last modified: 25th September 2010

Hide Menu


Valid XHTML Valid CSS
Valid RSS VIM Powered
RSS Feed Icon

This site uses Google Analytics to track visits. Privacy Statement

Page Icon
Download

Download Files
config.tar.gz

Java Configuration File API

This is a simple Java Configuration file API. It provides methods for reading key-value pairs from a file. The main benefit over using Java's standard Properties class is support for nested array configuration values. This implementation is inspired by, but somewhat more basic than libconfig, a very useful C/C++ Configuration File Library.


Configuration File Format and Retrieving Values

The configuration file is formatted in key-value pairs. The key is separated from the value using an equals sign and the value is terminated using a semicolon. Comments can be included using a hash character. Below is an example.

key = value; # A Comment

The code below shows how a new Config object is instantiated. It will load the configuration information from the file data.cfg.

try {
   Config config = new Config("data.cfg");
}
catch (ConfigException e) {
   System.err.println(e);
}

Primitive Type Values

Although configuration values are stored as strings a set of utility functions are available in the Config class for converting values to primitive types. Below is an example configuration.

num1 = 5;
num2 = 12.6;

These values can be retrieved using the following methods.

int num1 = config.getInt("num1");
float num2 = config.getFloat("num2");

There are similar methods for types long and double, these are getLong and getDouble respectively.

Boolean Type Values

Boolean configuration values are also supported. The supported value strings for true are 'true' (case insensitive) and '1'. The supported value strings for false are 'false' (case insensitive) and '0'. Below are some examples. The getBoolean method is used to retrieve a boolean value.

# These are all true
bool1 = true;
bool2 = True;
bool3 = 1;

# These are all false
bool1 = false;
bool2 = FALSE;
bool3 = 0;

Strings Values

Although configuration values are already stored as strings, the getString method allows more complex string formatting to be used within the configuration file. Strings are enclosed in double quotes. Strings can be split into sections which may spread over multiple lines. Special characters can be included using escape codes, these are \n, \r and \t. A double quote can be included using a \" and a slash using \\. Below is an example.

test = "This is a string split over "
       "multiple lines\nThis is the real second line, this is \"quoted\"";

This configuration value can be retrieved and output using the following code.

String test = config.getString("test");
System.out.println(test);

The output looks like this. The two string sections are combined and the escaped new-line and double-quote characters are inserted as an actual characters.

This is a string split over multiple lines
This is the real second line, this is "quoted"

Providing Default Values

When retrieving a configuration value, it is possible to specify a default value in case the key-value pair has not been specified in the configuration file. For example, given the method below, if the configuration file contains the key foo then that value will be returned, otherwise the specified default value, 24 will be returned.

int num = config.getInt("foo", 24);

Arrays

The configuration file format supports nested array values. The elements of the array can be of mixed type. Arrays are enclosed in brackets and their elements are separated with commas. Below is a simple configuration example.

foo = ("Sam", 33),
      ("Bob", 23),
      ("Will", 45);

The code below parses the whole array. The first step is to use the getElement method to retrieve the full, unaltered configuration value. Arrays are broken apart using the splitArray method. Nested arrays are split one level at a time. Having split the top level into a string array, each entry is subsequently split and the resulting parts are parsed into their expected types.

As array elements are not retrieved using a key, once retrieved using splitArray they are converted to their expected type using the parse... methods rather that the get... methods.

// Get the full configuration value for key 'foo'
String array = config.getElement("foo");

// Split the top level array
String[] entries = config.splitArray(array);

// Iterate through each sub-array string
for (String entry : entries)
{
   // Split the sub array into the two parts
   String[] parts = config.splitArray(entry);

   // Parse the parts into their proper types
   String name = config.parseString(parts[0]);
   int age = config.parseInt(parts[1]);

   // Output the values
   System.out.printf("%s is %d years old\n", name, age);
}

The output is shown below.

Sam is 33 years old
Bob is 23 years old
Will is 45 years old

Below is a more complex array value. The displayTree method can be used to output an array in a tree layout to stdout.

bar = (a, ("str" "ing", b), ((c,d), d));
(a, ("str" "ing", b), ((c,d), d))  Depth:1, Index:0, Parents:0, Length:3
 ├─ a ............................ Depth:2, Index:0, Parents:3, Length:1
 │
 ├─ "str" "ing", b ............... Depth:2, Index:1, Parents:3, Length:2
 │   ├─ "str" "ing" .............. Depth:3, Index:0, Parents:2, Length:1
 │   └─ b ........................ Depth:3, Index:1, Parents:2, Length:1
 │
 └─ (c,d), d ..................... Depth:2, Index:2, Parents:3, Length:2
     │
     ├─ c,d ...................... Depth:3, Index:0, Parents:2, Length:2
     │   ├─ c .................... Depth:4, Index:0, Parents:2, Length:1
     │   └─ d .................... Depth:4, Index:1, Parents:2, Length:1
     │
     └─ d ........................ Depth:3, Index:1, Parents:2, Length:1

System Properties

It is possible to override configuration values using system properties. This is makes it possible to override a value in a configuration file from the java invocation. Below is an example configuration file and a simple class that reads it.

File: data.cfg
foo = 14.703;
File: Test.java
public class Test
{
   public static void main(String[] args)
   {
      try
      {
         Config config = new Config("data.cfg", true, true);
         System.out.println(config.getDouble("foo"));
      }
      catch (ConfigException e)
      {
         System.err.println(e);
      }
   }
}

Below is shown the configuration value with key 'foo' when a system property of the same name is unset and set when Java is started.

> java Test
14.703
> java -Dfoo=9.456 Test
Override: foo = 9.456
9.456

Config API

Config Constructors

Config(String filename) throws ConfigException

Constructs a new Config object based on the configuration file with the specified filename.

Config(String filename, boolean useSysProperties, boolean showOverrides) throws ConfigException

Constructs a new Config object based on the configuration file with the specified filename. The useSysProperties argument can be used to enable overriding configuration file values with system property values. If the showOverrides argument is true, when a system property overrides a configuration file value, a message is printed to stdout.

String Retrieval Methods

String getElement(String key)

Returns the configuration value specified by the key string argument. This method should be used when retrieving array values. If the configuration value is a string, then getString should be used so the value is properly parsed. If the key is not found, null is returned.

String parseString(String val) throws ConfigException

Parses a configuration value of type string. This method combines separate double-quoted string sections and converts escaped characters into their proper encoded value. This method should be used when retrieving strings from within an array.

String getString(String key, String def) throws ConfigException

This method returns the configuration value linked to the specified key. If the key is not found, the default value specified by def is returned.

String getString(String key) throws ConfigException

This method returns the configuration value linked to the specified key. If the key is not found, a ConfigException is thrown.

Boolean Retrieval Methods

static boolean parseBoolean(String val) throws ConfigException

Parses a configuration value of type boolean. This method should be used when retrieving strings from within an array.

boolean getBoolean(String key, boolean def) throws ConfigException

Returns the configuration value linked to the specified key. The value is converted to a boolean type. If the conversion fails a ConfigException is thrown. If the key is not found, the default value specified by def is returned.

boolean getBoolean(String key) throws ConfigException

Returns the configuration value linked to the specified key. The value is converted to a boolean type. If the conversion fails a ConfigException is thrown. If the key is not found, null is returned.

Long Retrieval Methods

static long parseLong(String val) throws ConfigException

Same as boolean version, but for long type.

long getLong(String key, int def) throws ConfigException

Same as boolean version, but for long type.

long getLong(String key) throws ConfigException

Same as boolean version, but for long type.

Integer Retrieval Methods

static int parseInt(String val) throws ConfigException

Same as boolean version, but for int type.

int getInt(String key, int def) throws ConfigException

Same as boolean version, but for int type.

int getInt(String key) throws ConfigException

Same as boolean version, but for int type.

Float Retrieval Methods

static float parseFloat(String val) throws ConfigException

Same as boolean version, but for float type.

float getFloat(String key, float def) throws ConfigException

Same as boolean version, but for float type.

float getFloat(String key) throws ConfigException

Same as boolean version, but for float type.

Double Retrieval Methods

static double parseDouble(String val) throws ConfigException

Same as boolean version, but for double type.

double getDouble(String key, double def) throws ConfigException

Same as boolean version, but for double type.

double getDouble(String key) throws ConfigException

Same as boolean version, but for double type.

Array Retrieval Methods

static String[] splitArray(String str) throws ConfigException

This is the main method for working width arrays, it should be used in conjunction with the getElement method. Given a configuration value it will split it into sub strings leaving nested arrays intact. Each level of array needs to be split individually using this method.

Configuration Display Methods

void display(PrintStream out)

A helper method that outputs all the loaded configuration data.

static void displayTree(String str, boolean details) throws ConfigException

A helper method that outputs an array configuration value in a tree format. Set the details argument for extra info.


Book Logo