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.
data.cfg
foo = 14.703;
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(String filename, boolean useSysProperties, boolean showOverrides) throws ConfigException
Constructs a new |
String Retrieval Methods
String |
getElement(String key)
Returns the configuration value specified by the |
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 |
String |
getString(String key) throws ConfigException
This method returns the configuration value linked to the specified key. If the key is not found, a |
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
|
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
|
Long Retrieval Methods
static long |
parseLong(String val) throws ConfigException
Same as |
long |
getLong(String key, int def) throws ConfigException
Same as |
long |
getLong(String key) throws ConfigException
Same as |
Integer Retrieval Methods
static int |
parseInt(String val) throws ConfigException
Same as |
int |
getInt(String key, int def) throws ConfigException
Same as |
int |
getInt(String key) throws ConfigException
Same as |
Float Retrieval Methods
static float |
parseFloat(String val) throws ConfigException
Same as |
float |
getFloat(String key, float def) throws ConfigException
Same as |
float |
getFloat(String key) throws ConfigException
Same as |
Double Retrieval Methods
static double |
parseDouble(String val) throws ConfigException
Same as |
double |
getDouble(String key, double def) throws ConfigException
Same as |
double |
getDouble(String key) throws ConfigException
Same as |
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 |
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 |