Friday, 10 June 2011

Reading and Writing Property Files

Your application will usually need some configuration data that can be set-up prior to run-time and determines how your application runs. A common method for achieving this is to use a one or more property files and these are usually read and written using the Properties class.

This class has been been wrapped for simplicity by many different APIs, so the aim of this blog is to demonstrate that using the raw Properties class is very simple.

First we’ll cover writing some properties to a file. I’m assuming a simple scenario here: your application is running, a configuration property has being altered and it’s been written to a file.

  public static void writePropertiesDemo() throws IOException {

   
Properties p = new Properties();
    addValuesToProperties
(p);
    storeExampleProperties
(p, propertyFileName);
 
}

 
private static void addValuesToProperties(Properties p) {
   
p.setProperty("Key 1", "String 1");
    p.setProperty
("Key 2", "String 2");
    p.setProperty
("Key 3", "String 3");
    p.setProperty
("Key 4", "String 4");
    p.setProperty
("Key 5", "String 5");
    p.setProperty
("Key 6", "String 6");
 
}

 
private static void storeExampleProperties(Properties p, String propertyFileName)
     
throws IOException {

   
FileOutputStream fos = new FileOutputStream(propertyFileName);
    p.store
(fos, "My Test Properties (This is a comment)");
    fos.close
();
 
}

Note that I’ve used a FileOutputStream, but any OutputStream class will work just as well.

Having written some properties to a file, the next snippet of code demonstrates how to read them back in and display them on the console. This is the sort of code that runs when your application initialises itself.

  private static void readPropertiesDemo() throws IOException {

   
Properties p = new Properties();
    readPropertyFile
(p, propertyFileName);
    displayProperties
(p);
 
}

 
private static void readPropertyFile(Properties p, String propertyFileName)
     
throws IOException {
   
FileInputStream fis = new FileInputStream(propertyFileName);
    p.load
(fis);
 
}

 
private static void displayProperties(Properties p) {
   
// File contents are ready for use. In this case we just list them all on the screen
   
p.list(System.out);

   
// or pick individual ones out
   
System.out.println("\"Key 1\" has value \"" + p.getProperty("Key 1") + "\"");
 
}

No comments: