Tuesday 14 January 2014

Properties Class

We can used Property Class object to represent key-value pair were both key -value are of String type only.

In our program if there is anything which is change frequently(like database username ,password) never recommended to hard code in java program because of every change in java program we have to recompile,run  & deploy of application and even sometimes we may required to restart the server sometime these may cause business impact on client .

such type of variable(that may change frequently) we have to declare in file with extension .properties
The main advantage if there is any change in properties file  to reflect that change just redployment is enough ,which may not create business impact on client.  

Simple program to demonstrate Properties class :

//propertiesDemo.java

import java.io.*;
import java.util.*;
class propertiesDemo
{
    public static void main(String[] args) throws Exception
    {
        //System.out.println("Hello World!");
   
    Properties p=new Properties();
    FileInputStream f=new FileInputStream("kunal.properties");
    p.load(f);
    System.out.println(p);
    p.setProperty("kunu","1111");
    p.setProperty("courase","java") ;
    FileOutputStream f1=new FileOutputStream("kunal.properties");
    p.store(f1,"updates")
 }
}

//kunal.properties

#updates
#Tue Jan 14 19:44:12 IST 2014
user=scott
name=kunal
kunu=1111
courase=java
duration=four
pwd=tiger


Output:
c:\ocjp>JAVA propertiesDemo
{user=scott, name=kunal, kunu=1111, courase=java, duration=four, pwd=tiger}


in java program if we set property explicitly it also refelct in properties file and also
if we add any new property in kunal.properties it also refelect in console without compiling the java program.

No comments:

Post a Comment