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 file and just increment the value and again store in file. Each time we run this example it increment the count value.

 /* */

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(""));
            } 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);
            //set the new value of count
            //save the file
            try {
       FileOutputStream(""),"This is a simple example");
            } catch (IOException e) {
                System.out.println("IOException :: "+e);


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



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 "">
<comment>This is a simple example</comment>
<entry key="count">10</entry>

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