Sunday, May 26, 2013

Retrieve Key-Value Pairs of the Properties files in Java

Java  Properties class represents a persistent set of properties.

Properties class extends HashTable meaning Properties inherits from Hashtable, So put and putAll methods can be applied to a Properties object.

Some of useful methods are metioned below which object of Properties class can call.

Properties pro = new Properties();

  1. keySet() - Retrieve Set of Keys 
  2. keys() - Retrieves all keys of the properties files. Which stored in the Enumeration objects.
Once you have all keys from Properties file,You require to iterate it and for that purpose Enumeration can be used.  

Enumeraton is interface which provided by the java.util package.There are two important methods

1. hasMoreElements() - It will returns true, if the Enumeration object has more than one elements Otherwise, it return false.
2. nextElement() - If there are more next elements available then nextElement returns next elements of the Enumeration

Java Program to Load and Read Key Values of Properties File :

package com.anuj.utils;

import java.util.Enumeration;
import java.util.Properties;

 * @author Anuj
public class PropertyOperations {
 public static void main(String[] args) {

  Properties properties = new Properties();
  try {
   File file = new File("");
   FileInputStream fileInputStream = new FileInputStream(file);

   //load properties file

   System.out.println("keys avialble in Properties Files are:");

   System.out.println("Key Value Pairs :");
   Enumeration enumeration = properties.keys();
   while (enumeration.hasMoreElements()) {
    String key = (String) enumeration.nextElement();
    System.out.println(key + ": " + properties.get(key));
  } catch (IOException e) {

Output :

keys avialble in Properties Files are:
[age, name, property.2, property.1]
Key Value Pairs :
age: 25
name: anuj
property.2: Value of property 2.
property.1: Value of property 1.

Author : Anuj Patel
Blog :

No comments:

Post a Comment