Monday, August 23, 2010

Java : Simple Properties Example

The Properties class represents a persistent set of properties. The Properties can be saved to a stream or loaded from a stream. Each key and its corresponding value in the property list is a string.

Properties class extends Hashtable so methods like get, hashCode, isEmpty, keys, keySet, put, putAll, rehash, remove, size can be applied to Properties class.

Lets see a simple Java Properties counter example, here we will read count values ie load value from a  data.properties file and just increment the value and again store in data.properties file. Each time we run this example it increment the count value.

 /* PropertiesExample.java */

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

public class PropertiesExample {

        public static void main(String[] args) {
      
            Properties prop = new Properties();
           
            //load Properties prop from a file
            try {
                prop.load(new FileInputStream("data.properties"));
               
            } catch (IOException e) {
                System.out.println("IOException :: "+e);
            }
           
            //get values of count
            String count = prop.getProperty("count");
           
            System.out.println("count = "+count);
           
            //just incrementing value of count
            int newCount = Integer.parseInt(count);
            newCount++;
           
            //set the new value of count
            prop.setProperty("count",""+newCount);
           
            //save the file
            try {
                prop.store(new FileOutputStream("data.properties"),"This is a simple example");
               
            } catch (IOException e) {
                System.out.println("IOException :: "+e);
            }
           
    }

}


data.properties

#This is a simple example
#Mon Aug 23 13:05:22 IST 2010
count=12

Output










  














However you can also store / load the data in XML (.xml) file rather than .properties file using storeToXML(OutputStream os, String comment)and loadFromXML(InputStream in) method.

Also you can iterate through all parameters in Properties using propertyNames()and stringPropertyNames().

Lets look at API for more details

For eg. Data.xml
 
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>This is a simple example</comment>
<entry key="count">10</entry>
</properties>



properties file example

# this is a comment
! this is also a comment
a = a string
b = a string with escape sequences \t \n \r \\ \" \' \ (space) \u0123
c = a string with a continuation line
   \ continuation line
d.e.f = another string 


No comments:

Post a Comment