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.Objectjava.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 classpathInputStream 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 pairSystem.out.println("City Name = "+properties.getProperty("city"));}}
- (2) message.properties
- name=Johny kumarprofile =Java developercompany=Velocis System Pvt Ltd
- Note:- put the message.properties file in same directory as .class file
- Output on Console...
- ------------------------Employee Record --------------------Employee Name = Johny kumarJob Profile = Java developerCompany Name = Velocis System Pvt LtdAdding a key/value pair to message.propties fileCity Name = Noida
- Please Comment if any mistake ....
- Johny kumar (Java developer )
No comments:
Post a Comment