Simple Java Configuration Files and no XML in Sight

The last time I discussed Java configuration files it was from the point of locating them on the disk the right way. This time I want to comment on the content of configuration files. There seems to be an obsession with XML in the modern world. Some people seem to think that shoe-horning XML into their applications will somehow magically make them great. I don’t want to completely put down XML because it most certainly has its uses. In fact I use it quite a bit to store complex and potentially incomplete data sets. However, using XML to store simple configuration information is over-kill and makes the configuration file needlessly complex to edit and needlessly complicates your application. Unless you’re writing something huge or some thing complex the chances are you’re configuration file won’t need to be complicated. The chances are all you really need are some name-value pairs to specify a few parameters. If this is the case Java comes with a wonderfully simple solution right out of the box, .properties files.

[tags]Java, XML, Configuration Files[/tags]

The syntax for a .properties file could not be simpler; all lines beginning with a # are comments and all other lines are in the form:

<key>=<value>

Below is a sample configuration for the Virtual Learning environment I’m working on:

# Basic portal config
BASE_URL=www.eve.nuim.ie/evePortal

# Database stuff
DB_JNDI_NAME=jdbc/eve_portal

# File locations
DATA_DIR=/var/eve-data
PDFLATEX_BIN=/opt/local/bin/pdflatex
IMAGEMAGICK_BIN_DIR=/opt/local/bin

If you choose to use this type of configuration file you can locate and open it all in one step by using functionality built into the java class loader as follows:

Properties configFile = new Properties();
configFile.load(this.getClass().getClassLoader().getResourceAsStream("/my_config.properties"));

You can they read out any key in the following way:

some_var = configFile.getProperty("some_key");

Simple as that, no need to load complex parsing libraries, no big long messy code. Unless you have a good reason to go with a more complex format you really should be using .properties files.