Monday, 11 September 2017

How to read and write to .properties file in java


Properties class object provide facility to read and write  the key/value pair from .properties file . 
key and value both are String class object . java.util .Properties class is subclass of Hashtable .



                                                                                                                                                                                                        

java.lang.Object
                      java.util.Dictionary<K,V>
                                                      java.util.Hashtable<Object,Object>
                                                                                                           java.util.Properties

Since JDK 1.0 
Recompilation is not required, if information is changed from properties file: If any information is changed from the properties file, you don't need to recompile the java class. It is used to store information which is to be changed frequently.
Example of Read and write to .properties  file 
(1) PropertiesTest.java
(2) message.properties 

PropertiesTest.java
package in.jk;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class PropertiesTest {
public static void main(String[] args) throws IOException {
Properties properties = new Properties();
// reading .properties file from classpath 
InputStream inputstream     =  null;                                                                                                                                                       inputStream= PropertiesTest.getResourceAsStream("/message.properties");
properties.load(inputstream);
System.out.println();
System.out.println("------------Employee Record --------------");
System.out.println();
System.out.println("Employee Name = "+properties.getProperty("name"));
System.out.println("Job Profile   = "+properties.getProperty("profile"));
System.out.println("Company  = "+properties.getProperty("company"));
      System.out.println();
System.out.println("Adding a key/value pair to message.propties file ");
System.out.println();
properties.setProperty("city", "Noida"); // setting the a key/value pair 
System.out.println("City Name  = "+properties.getProperty("city"));
}

}

(2) message.properties 
name=Johny kumar
profile =Java developer
company=Velocis System Pvt Ltd

Note:- put the message.properties file in same directory as .class file 

Output on Console...

------------------------Employee Record --------------------

Employee Name = Johny kumar
Job Profile   = Java developer
Company Name  = Velocis System Pvt Ltd

Adding a key/value pair to message.propties file 

City Name  = Noida








Please Comment if any mistake ....
Johny kumar (Java developer )

No comments:

Post a Comment