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.

Technorati 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:

  1. <key>=<value>

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

  1. # Basic portal config
  2. BASE_URL=www.eve.nuim.ie/evePortal
  3.  
  4. # Database stuff
  5. DB_JNDI_NAME=jdbc/eve_portal
  6.  
  7. # File locations
  8. DATA_DIR=/var/eve-data
  9. PDFLATEX_BIN=/opt/local/bin/pdflatex
  10. 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:

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

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

  1. 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.