Jump to Real's How-to Main page

Use an INI file (properties)

In Java, configuration file are stored in properties file. By convention, the filename extension is props or properties. The structure 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, this one and finally this one too!
If you find this article useful, consider making a small donation
to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998-2005
[ home ]