Tuesday, August 28, 2007

Load Configuration file Using Java Code

In Java, configuration file are stored in properties file. By convention, the filename extension is props or properties.

NOTE: The structure is very similar to Windows INI file with except that there is no [...] section.

[Props file : user.properties]

# this a comment
! this a comment too
db.user=anonymous
db.password=&8djsx
db.location=bigone

[JAVA code]

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

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

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

We manipulate the Properties through the get and put methods. The modified data can be saved back to a file with the store method. This can be useful to store user preferences for example.
Note that the order and the comments are not preserved.

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

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

public void doit() {
try{
Properties p = new Properties();
p.load(new FileInputStream("user.properties"));
p.list(System.out);
// new Property
p.put("today", new Date().toString());
// modify a Property
p.put("db.password","foo");
FileOutputStream out = new FileOutputStream("user.properties");
p.store(out, "/* properties updated */");
}
catch (Exception e) {
System.out.println(e);
}
}
}

Note : This is 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());

1 comments:

pbsl said...

you have nice site. thanks for sharing this site. various kinds of ebooks are available here

http://feboook.blogspot.com

BidVertiser