Thursday, 21 November 2013

How to get values from properties file in Java by a custom method

application.properties

password.url = http://192.0.0.1:8080/Sample/resetpassword
portal.url=http://192.0.0.1:8080/Sample/home.html

Constants.java
package com.tb.module.service;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

public class Constants {

 public static final String jsp=getResetPasswordLink();
 public static final String portalLink=getPortalLink();


 public static String getResetPasswordLink(){

     try {
      Properties prop = new Properties(); 
      //load a properties file
      prop.load(Constants.class.getClassLoader()
.getResourceAsStream("application.properties"));
               //get the property value and print it out
             return prop.getProperty("password.url");
     } catch (IOException ex) {
      ex.printStackTrace();
      return null;
        }
  
 }
 
 public static String getPortalLink(){

     try {
      Properties prop = new Properties(); 
      //load a properties file
      prop.load(Constants.class.getClassLoader()
.getResourceAsStream("application.properties"));
               //get the property value and print it out
             return prop.getProperty("portal.url");
     } catch (IOException ex) {
      ex.printStackTrace();
      return null;
        }
  
 }
 
}

We can use 
Constants.jsp
Constants.portalLink 

No comments: