Easy Find Mutable Config Files In Java

When developing cross-platform applications in Java or other languages, a common problem (and source of user errors) is where to store (and thus later, find) configuration files. We typically need configuration files because (in Java: barring the somewhat young and untrusted Preferences API) there is no other reliable cross-platform method. Ideally, they should be:

Ive encountered many difficulties fulfilling these requirements as a developer myself, and used enough 3rd party java applications that are hard to configure to know Im not alone.

The first requirement is often solved by loading resources through the classpath, using the ClassLoader.getResource() family of methods. This is a good solution because for the app to be running at all, the classpath must be basically correct to locate out config file. One needs to be careful which ClassLoader you use; I use getClass().getClassLoader() myself.

What the http://jakarta.apache.org/commons/configuration implemntation taught me, that isnt widely realized, is that one can convert the URL returned by getRecource() back into a writeable file. Thus, it is possble to locate a config file from the classpath only, but then write back to it. The XMLConfiguration class from the Apache commons configuration API is a nice example of the technique in action.

The catch is that you need to have a file on disk, and not in a JAR, so the distibution does need to be exploded out :(


EditText of this page (last edited August 31, 2004) or FindPage with title or text search