tags:

views:

5438

answers:

5

I am writing a drop-in replacement for a legacy application in Java. One of the requirements is that the ini files that the older application used have to be read as-is into the new Java Application. The format of this ini files is the common windows style, with header sections and key=value pairs, using # as the character for commenting.

I tried using the Properties class from Java, but of course that won't work if there is name clashes between different headers.

So the question is, what would be the easiest way to read in this INI file and access the keys?

+16  A: 

The library I've used is ini4j. It is lightweight and parses the ini files with ease. Also it uses no esoteric dependencies to 10,000 other jar files, as one of the design goals was to use only the standard Java API

This is an example on how the library is used:

Preferences prefs = new IniFile(new File(filename));
System.out.println("grumpy/homePage: " + prefs.node("grumpy").get("homePage", null));
Mario Ortegón
Link: http://ini4j.sourceforge.net/
alastairs
+2  A: 

Another option is Apache Commons Config also has a class for loading from INI files. It does have some runtime dependencies, but for INI files it should only require Commons collections, lang, and logging.

I've used Commons Config on projects with their properties and XML configurations. It is very easy to use and supports some pretty powerful features.

John Meagher
A: 

Or with standard Java API you can use java.util.Properties

new Properties() props = rowProperties.load(new FileInputStream(path));
Peter
Problem is that, with ini files, the structure has headers. The Property class does not know how to handle the headers, and there could be name clashes
Mario Ortegón
+2  A: 

Using the apache class "HierarchicalINIConfiguration" "http://commons.apache.org/configuration/apidocs/org/apache/commons/configuration/HierarchicalINIConfiguration.html". Its simple, and yet powerful.

HierarchicalINIConfiguration iniConfObj = new HierarchicalINIConfiguration(iniFile); 

// Get Section names in ini file        
Set setOfSections = iniConfObj.getSections();
Iterator sectionNames = setOfSections.iterator();

while(sectionNames.hasNext()){

    String sectionName = sectionNames.next().toString();

    SubnodeConfiguration sObj = iniObj.getSection(sectionName);
    Iterator it1 =   sObj.getKeys();

    while (it1.hasNext()) {
    // Get element
    Object key = it1.next();
    System.out.print("Key " + key.toString() +  " Value " +  
                     sObj.getString(key.toString()) + "\n");
  }

Dependency: commons-collections-3.2.1 Jar

Arun ~ arunky

A: 

When using HierarchicalINIConfiguration, I found that a single dot in the key is always translated to double dots. For example, for this entry in INI file: hbase.hbase-site.ciq.hbase.striping=1 I got: Key hbase..hbase-site..ciq..hbase..striping Value 1

Has anyone else encountered this issue ?

Ted Yu