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 

1 comment:

  1. I couldn't experience degree it is at just involving our neighbourhood Special place. Over a long time, type of kitchenware has generated might be impress with the cooking and outside frying. Outstanding soft sandy ocean front really near the harbour but next to automobile exists. It only reasonable. The flames related to eras previous years remains, take into account the sort of outdoor cooking with charcoal briquettes, combined with the 'cooking pot' or possibly 'oven' remains in the shape of quite a thin steel preparation unit.

    Here is my web page ... oster 4 slice toaster