Sunday 19 February 2012

Reading properties file java

Reading properties file in java:

Properties file in java is a simple key value file where key and value is separated by  '='.

Below example reads properties files and displays all the elements in it.

Config.properties is a property file.
 
 
#configuration properties
#key=value
username=abc
password=123
PropertyReader reades the config.properties
 

package demo;

import java.io.FileInputStream;
import java.util.Properties;
/**
 * Reads properties file and display all the contents in it
 * @author luckyacademy
 *
 */
public class PropertyReader {
 public static void main(String[] args) throws Exception {
  
  //open input stream to properties file
  FileInputStream fin = new FileInputStream("config.properties");
  Properties pr = new Properties();
  
  // read properties file
  pr.load(fin);
  
  //read value for key username
  System.out.println("Reading value: " + pr.getProperty("username"));

  //display all properties in file.
  for(Object key:pr.keySet()){
   System.out.println("Key: "+key+ " Value: "+pr.getProperty((String)key));
  }
  
  //close the properties file
  fin.close();
 }
}

No comments:

Post a Comment