View RSS Feed

My Java Tips

Using property files

Rate this Entry
by , 11-07-2011 at 06:05 PM (564 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:


mode=alert
packet=realTime

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("sample.properties");
    prop.load(fis);
    prop.list(System.out);
    System.out.println("nThe foo property: " +
        prop.getProperty("foo"));
  }
}


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{
      h.doit();
      h.doitagain();
      }
   public void doit() throws Exception{
      // properties in the classpath
      java.util.Properties props = new java.util.Properties();
      java.net.URL url = ClassLoader.getSystemResource("myprops.props");
      props.load(url.openStream());
      System.out.println(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);
      java.io.FileInputStream fis = new java.io.FileInputStream
         (new java.io.File( path + "\myprops.props"));
      props.load(fis);
      System.out.println(props);
     }
}
Hope this helps.

Submit "Using property files" to Facebook Submit "Using property files" to Digg Submit "Using property files" to del.icio.us Submit "Using property files" to StumbleUpon Submit "Using property files" to Google

Tags: None Add / Edit Tags
Categories
Java SE

Comments