Thursday, 20 November 2008

Read and write to .properties and .ini files

It is usual to store settings or properties of an application in some of these 5 known ways:

- to DB
- to XML
- to .ini file
- to .properties file
- to registry

My favorite are XML and .ini/.properties file.
All of them has some kind of restrictions, and it’s really up to data type that application needs to save , and which programming language I’m using at that moment…

If my application needs to read/save small number of information, without complex scheme of sections, then I always use .properties or .ini files.

To be honest, first time I used ( Java )class that works with .properties files, I was very surprised how easy is it to read/write settings. And all of that with small-size code, which is not usual in Java. ( Look at my earlier blog about parsing a document in PHP and Java : http://devtalks.blogspot.com/2008/09/parsing-xml-php-vs-java_16.html )

In Java, in order to work with .properties files, there’s a Properties class. Properties class extends HashTable , so we manipulate properties through the get and set methods.
It’s quite easy and fun to work with it.
Let’s say we have some file: example.properties, and it looks something like this:

We could easily parse it like this:

or, write current properties in application into the file with:

If we write

public static void main(String args[])
{
Main main = new Main();
main.readProperties();
}

the result would be:

color= blue
width= 150
height= 100

color= bluewidth= 150height= 100
The other way around, if we write

public static void main(String args[])
{
Main main = new Main();
main.saveProperties();
}

the example.properties file would look like this:

but, as you can see, without any particular order among properties that we wrote.

As I sad, I didn’t used to write something in Java with such small code size, and it feels great… :-)

All of this reminds me of TIniFile class in Borland Builder, and it is very hard to catch up with BCB when it comes to simplicity ( in my opinion, that is…).

Let’s take a look how we would do this in BCB. Ini files are very similar to .properties files. The difference is that .ini files have sections, and .properties doesn’t.

Let’s make a test application:

and let’s say we have file example.ini with a "data" section, and is looks something like this:

and we need to write these settings in appropriate Edits on the Form when someone starts the application. At exit, we need to overwrite properties in a file with those that are in these three Edits at that moment…