Sunday, May 8, 2016

How to load Properties file from a static block or static method?

Description:
This example shows how to load properties file with in a static block or static method. Here we are using ClassLoader.class.getResourceAsStream() to load the properties file in the classpath within static block. Make sure that the class is available in the class path

Code:

package com.java2novice.properties;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class MyPropInStaticBlock {
    private static Properties prop;
     
    static{
        InputStream is = null;
        try {
            prop = new Properties();
            is = ClassLoader.class.getResourceAsStream("/sample.properties");
            prop.load(is);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
     
    public static String getPropertyValue(String key){
        return prop.getProperty(key);
    }
     
    public static void main(String a[]){
         
        System.out.println("db.host: "+getPropertyValue("db.host"));
        System.out.println("db.user: "+getPropertyValue("db.user"));
        System.out.println("db.password: "+getPropertyValue("db.password"));
    }
}

sample.properties

db.host=appdomain.java2novice.com
db.user=java2novice
db.password=mypassword
db.service=orcl

Output:

db.host: appdomain.java2novice.com
db.user: java2novice
db.password: mypassword

No comments:

Post a Comment