View RSS Feed

My Java Tips

Using property files

Rate this Entry
by , 11-07-2011 at 07:05 PM (710 Views)
To make your Java applications flexible, you might want to give properties that keep on changing in properties file. A property file is simply a text file that has key-value pairs relation.

If you are thinking of writing your parser to read the property files, then think again. Java provides java.util.Properties class, that will help you deal with propery files. Property files comprise of key-value pairs in a file, where the key and value are separated by an equal sign. Foe example:


Now the idea is to load the property file into Properties object. Then you will have two keys (mode and packet) and two values (alert and realTime). The Properties class supports embedding Unicode strings with \u. Remember, everything is treated as a String.

Now lets see how to code it:

Java Code:
public class LoadSample {
  public static void main(String args[]) throws Exception {
    Properties prop = new Properties();
    FileInputStream fis =
      new FileInputStream("");
    System.out.println("nThe foo property: " +

The Properties class stores the set of pairs in a hashtable, so there is no guarantee for order. Another interesting example of loading property file is given below:

Java Code:
public class LoadProps {

   public static void main(String args[]) throws Exception{
   public void doit() throws Exception{
      // properties in the classpath
      java.util.Properties props = new java.util.Properties(); url = ClassLoader.getSystemResource("myprops.props");
   public void doitagain() throws Exception{
      // properties in the startup directory
      java.util.Properties props = new java.util.Properties();
      String path = getClass().getProtectionDomain().getCodeSource().
                    getLocation().toString().substring(6); fis = new
         (new path + "\myprops.props"));
Hope this helps.

Submit "Using property files" to Facebook Submit "Using property files" to Digg Submit "Using property files" to Submit "Using property files" to StumbleUpon Submit "Using property files" to Google

Tags: None Add / Edit Tags
Java SE