Share this page 

Use an INI file (properties)Tag(s): Language


Open Source packages
The ini4j is a simple Java API for handling configuration files in Windows .INI format.

http://ini4j.sourceforge.net/

As a bonus, ini4j can deal with variable subsitution, parse .REG file and write or read the registry.

The Apache Commons Configuration package provides the HierarchicalINIConfiguration class to handle Windows INI file.

http://commons.apache.org/configuration/

Using Properties
The structure of a Properties is very similar to Windows INI file with except that there is no [...] section.

[Props file : user.props]

# this a comment
! this a comment too
DBuser=anonymous
DBpassword=&8djsx
DBlocation=bigone

[JAVA code]

import java.util.*;
import java.io.*;

class ReadProps {
  public static void main(String args[]) {
    ReadProps props = new ReadProps();
    props.doit();
  }

  public void doit() {
    try{
      Properties p = new Properties();
      p.load(new FileInputStream("user.props"));
      System.out.println("user = " + p.getProperty("DBuser"));
      System.out.println("password = " + p.getProperty("DBpassword"));
      System.out.println("location = " + p.getProperty("DBlocation"));
      p.list(System.out);
    }
    catch (Exception e) {
      System.out.println(e);
    }
  }
}

Since the Properties class extends the Hashtable, we can manipulate the Properties through the get and put methods. The modified data can be saved back to a file with the save method. This can be useful to store user preferences for example. Note that the order is not preserved.

import java.util.*;
import java.io.*;

class WriteProps {
  public static void main(String args[]) {
    WriteProps props = new WriteProps();
    props.doit();
  }

  public void doit() {
    try{
      Properties p = new Properties();
      p.load(new FileInputStream("user.props"));
      p.list(System.out);
      // new Property
      p.put("today", new Date().toString());
      // modify a Property
      p.put("DBpassword","foo");
      FileOutputStream out = new FileOutputStream("user.props");
      p.save(out, "/* properties updated */");
    }
    catch (Exception e) {
      System.out.println(e);
    }
  }
}
This ok with an application but you can't do it from an Applet since you can't write directly on the server without some kind of a server-side process.

To read a Properties file via an Applet, load the Properties files this way :

p.load((new URL(getCodeBase(), "user.props")).openStream());
A Properties file stored in a JAR can be loaded this way :
URL url =
   ClassLoader.getSystemResource("/com/rgagnon/config/system.props");
if (url != null) props.load(url.openStream());
See also this HowTo (Load a properties file), this one (Accentuated characters in Properties/ResourceBundle file) and finally this one too (Have a multi-line value in a properties file)!