Sunday, 28 July 2013

How to load and read the Property file from classpath in java?


Loading and Reading the Property file from classpath in java

Properties files are the important resources to store information in Java. These files are used to store static information as key and value pair.



There are ways to Load the property file in java.

1. With the help of getClassLoader().getResourceAsStream(fileName)
2. With the help of getClass().getResourceAsStream(fileName) 

In the below example, we will use above both the methods to load the properties files from the classpath:-

Content of the Test.properties file:-

NAME=KUMAR GAURAV
EMP_ID=1234
ORG_NAME=INDIA COMPANY


A program to load and read the property file from classpath.

package com.gaurav.loadpropertyfile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.Set;

public class PropertyFileLoader {
            /**
             * This method is responsible to load a property file.
             *
             * @return Properties
             */
            public static Properties loadPropertyFile(String fileName) {
                        Properties prop = null;
                        try {
                                    prop = new Properties();
                                    InputStream in = PropertyFileLoader.class.getClassLoader()
                                                            .getResourceAsStream(fileName);
                                    prop.load(in);
                                    in.close();
                        } catch (IOException ioe) {
                                    System.out.println(ioe.getMessage());
                        }
                        return prop;
            }

            /**
             * This method is responsible to load a property file without using getClassLoader() method.
             *
             * @return Properties
             */
            publicProperties loadPropertyFileUsingSecondWay(String fileName) {
                        Properties prop = null;
                        try {
                                    prop = new Properties();
                                    InputStream in = this.getClass().getResourceAsStream(fileName);
                                    prop.load(in);
                                    in.close();
                        } catch (IOException ioe) {
                                    System.out.println(ioe.getMessage());
                        }
                        return prop;
            }

            /**
             * This method is responsible to load the property by reading from the file.
             *
             * @return String
             */
            public static String getPropertyValue(Properties prop, String propertyKey) {
                        String propertyValue = null;
                        boolean flag = prop.containsKey(propertyKey);
                        if (flag) {
                                    propertyValue = prop.getProperty(propertyKey);
                        }
                        return propertyValue;
            }

            @SuppressWarnings("rawtypes")
            public static void main(String args[]){
                        Properties prop = new Properties();
                        prop = PropertyFileLoader.loadPropertyFile("Test.properties");
                        Set propertySet = prop.entrySet();
                        System.out.println("AVAILABLE PROPERTIES ARE \n");
                        for( Object obj :propertySet){
                                    System.out.println(obj);
                        }
                        /** Checking the available properties in the property file*/
                        String propValue=PropertyFileLoader.getPropertyValue(prop, "ORG_NAME");
                        System.out.println("\nORG_NAME key property Value is-"+propValue);

                        /** Again Loading the property file using second method*/
                        PropertyFileLoader pfl = new PropertyFileLoader();
                        Properties prop1 = new Properties();
                        prop1 = pfl.loadPropertyFileUsingSecondWay("/com/gaurav/loadpropertyfile/employee.properties");
                        Set propertySet1 = prop1.entrySet();
                        System.out.println("\nAVAILABLE PROPERTIES USING SECOND METHOD ARE \n");
                        for( Object obj :propertySet1){
                                    System.out.println(obj);
                        }
                        /** Checking the available properties in the property file*/
                        String propValue1 =PropertyFileLoader.getPropertyValue(prop1, "COMP_NAME");
                        System.out.println("\nCOMP_NAME key property Value is-"+propValue1);
            }
}


Result:-


AVAILABLE PROPERTIES ARE

EMP_ID=1234
ORG_NAME=INDIA COMPANY
NAME=KUMAR GAURAV

ORG_NAME key property Value is-INDIA COMPANY

AVAILABLE PROPERTIES USING SECOND METHOD ARE

ID=9876
COMP_NAME=COMPANY LTD
EMP_NAME=EMPLOYEE 1

COMP_NAME key property Value is-COMPANY LTD


How to read the PLAIN property file and XML property file in java?



Below example is used to read the plain text property file as well as the XML format property file.

packagecom.gaurav.loadpropertyfile;

importjava.io.FileInputStream;
importjava.io.FileNotFoundException;
importjava.io.FileReader;
importjava.io.IOException;
importjava.io.InputStream;
importjava.util.Properties;
importjava.util.Set;

public class PropertyFileReader {

                public static void main(String[] args) throws IOException {
                                // This property is used for writing the File.
                                String plainPropertyFileName = "src/jdbc.properties";
                                String xmlPropertyFileName = "src/jdbc.xml";
                                /**
                                 * For reading the property from classpath no need to pass src
                                 * directory, as reading from classpath means automatically it will
                                 * search in the src directory and if file is not found then it will
                                 * throw Null Pointer Exception
                                 */
                                // This property is used for reading the File from classpath.
                                String propFileNameFromClasspath = "jdbc.properties";
                                getAllPropertyKeysFromFiles(plainPropertyFileName, xmlPropertyFileName);
                                getPropertiesFromFiles(plainPropertyFileName, xmlPropertyFileName);
                                getPropFileFromClasspath(propFileNameFromClasspath);
                }

                /**
                 * read property file from java classpath
                 *
                 * @param plainPropertyFileName
                 * @throws IOException
                 */
                private static voidgetPropFileFromClasspath(String plainPropertyFileName)
                                                throws IOException {
                                Properties prop = new Properties();
                                prop.load(PropertyFileReader.class.getClassLoader()
                                                                .getResourceAsStream(plainPropertyFileName));
                                System.out.println("Reading property file " + plainPropertyFileName
                                                                + " from the classpath");
                                System.out.println("jdbc.driverClassName = "
                                                                + prop.getProperty("jdbc.driverClassName"));
                                System.out.println("jdbc.url = " + prop.getProperty("jdbc.url"));
                                System.out.println("jdbc.username = "
                                                                + prop.getProperty("jdbc.username"));
                                System.out.println("jdbc.password = "
                                                                + prop.getProperty("jdbc.password"));
                                System.out
                                                                .println("Execution completed for reading property file "
                                                                                                + plainPropertyFileName + " from the classpath");
                                System.out
                                                                .println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");

                }

                /**
                 * read all the keys from the given property files
                 *
                 * @param plainPropertyFileName
                 * @param xmlPropertyFileName
                 * @throws IOException
                 */
                private static voidgetAllPropertyKeysFromFiles(
                                                String plainPropertyFileName, String xmlPropertyFileName)
                                                throws IOException {
                                System.out
                                                                .println("Execution started for getting all property Keys from files");
                                Properties prop = new Properties();
                                FileReader reader = new FileReader(plainPropertyFileName);
                                prop.load(reader);
                                Set<Object> keys = prop.keySet();
                                System.out.println("Reading keys from " + plainPropertyFileName
                                                                + " property file started");
                                for (Object obj : keys) {
                                                System.out.println("Key=" + obj.toString() + "||value="
                                                                                + prop.getProperty(obj.toString()));
                                }
                                // clearing existing properties and loading xml file
                                System.out.println("Reading keys from " + plainPropertyFileName
                                                                + " property file completed\n");
                                prop.clear();
                                InputStream is = new FileInputStream(xmlPropertyFileName);
                                prop.loadFromXML(is);
                                keys = prop.keySet();
                                System.out.println("Reading keys from " + xmlPropertyFileName
                                                                + " property file started");
                                for (Object obj : keys) {
                                                System.out.println("Key=" + obj.toString() + "||value="
                                                                                + prop.getProperty(obj.toString()));
                                }
                                System.out.println("Reading keys from " + xmlPropertyFileName
                                                                + " property file completed");
                                // closing and closing all the resources
                                is.close();
                                reader.close();
                                System.out
                                                                .println("Execution completed for getting all property Keys from files\n");
                                System.out
                                                                .println("******************************************************************\n");
                }

                /**
                 * This method reads plain property as well as XML property files from file
                 * system
                 *
                 * @param plainPropertyFileName
                 * @param xmlPropertyFileName
                 * @throws IOException
                 * @throws FileNotFoundException
                 */
                private static void getPropertiesFromFiles(String plainPropertyFileName,
                                                String xmlPropertyFileName) throws FileNotFoundException,
                                                IOException {
                                System.out.println("Start of getting properties from files");
                                Properties prop = new Properties();
                                FileReader reader = new FileReader(plainPropertyFileName);
                                prop.load(reader);
                                System.out.println("Reading " + plainPropertyFileName
                                                                + " property file started");
                                System.out.println("jdbc.driverClassName = "
                                                                + prop.getProperty("jdbc.driverClassName"));
                                System.out.println("jdbc.url = " + prop.getProperty("jdbc.url"));
                                System.out.println("jdbc.username = "
                                                                + prop.getProperty("jdbc.username"));
                                System.out.println("jdbc.password = "
                                                                + prop.getProperty("jdbc.password"));
                                System.out.println("Reading " + plainPropertyFileName
                                                                + " property file completed\n");
                                // loading xml file now, first clear existing properties
                                prop.clear();
                                InputStream is = new FileInputStream(xmlPropertyFileName);
                                prop.loadFromXML(is);
                                System.out.println("Reading " + xmlPropertyFileName
                                                                + " property file started");
                                System.out.println("jdbc.driverClassName = "
                                                                + prop.getProperty("jdbc.driverClassName"));
                                System.out.println("jdbc.url = " + prop.getProperty("jdbc.url"));
                                System.out.println("jdbc.username = "
                                                                + prop.getProperty("jdbc.username"));
                                System.out.println("jdbc.password = "
                                                                + prop.getProperty("jdbc.password"));
                                System.out.println("Reading " + xmlPropertyFileName
                                                                + " property file completed");
                                // closing and Releasing all the resources
                                is.close();
                                reader.close();
                                System.out.println("End of getting properties from files");
                                System.out
                                                                .println("####################################################################\n");
                }

}

Result:-

Execution started for getting all property Keys from files
Reading keys from src/jdbc.properties property file started
Key=jdbc.username||value=root
Key=jdbc.password||value=root
Key=jdbc.driverClassName||value=com.mysql.jdbc.Driver
Reading keys from src/jdbc.properties property file completed

Reading keys from src/jdbc.xml property file started
Key=jdbc.username||value=system
Key=jdbc.password||value=system123
Key=jdbc.driverClassName||value=oracle.jdbc.driver.OracleDriver
Reading keys from src/jdbc.xml property file completed
Execution completed for getting all property Keys from files

******************************************************************

Start of getting properties from files
Reading src/jdbc.properties property file started
jdbc.driverClassName = com.mysql.jdbc.Driver
jdbc.url = null
jdbc.username = root
jdbc.password = root
Reading src/jdbc.properties property file completed

Reading src/jdbc.xml property file started
jdbc.driverClassName = oracle.jdbc.driver.OracleDriver
jdbc.url = null
jdbc.username = system
jdbc.password = system123
Reading src/jdbc.xml property file completed
End of getting properties from files
####################################################################

Reading property file jdbc.properties from the classpath
jdbc.driverClassName = com.mysql.jdbc.Driver
jdbc.url = null
jdbc.username = root
jdbc.password = root
Execution completed for reading property file jdbc.properties from the classpath
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~