Sunday, April 15, 2018

How to read value from property file in java


In the tutorial , we will talk about how to read value from property files in java program. As we all know that property file are the best choice when it comes to configure the program without changing it's code. so lets see how to read value from property file in java


Le suppose we have a program where we are reading the values from property file in resource. Below is the code we would use.
You can download the source code from GitHub
The project Structure


Now look for App.java Code 

package com.programinjava.learn.ReadPropertyFileDemo;

/**
 * Read property file demo
 *
 */
public class App 
{
    public static void main( String[] args )
    {
//       Now I will read the property value of property-key
    	String valueOfKey = PropertyUtil.readProperty("property-key");
    	System.out.println(valueOfKey);
    }
}

PropertyUtil Class Code:


package com.programinjava.learn.ReadPropertyFileDemo;

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

public class PropertyUtil {
//	define the path of property file 
private static final String PROPERTY_FILE_PATH="src/main/resources/app.properties";	
	public static String readProperty(String propName) {
		Properties prop = new Properties();
		InputStream input = null;
		String propValue = null;
		try {
			input = new FileInputStream(PROPERTY_FILE_PATH);
			prop.load(input);
			propValue = prop.getProperty(propName);
		} catch (IOException ex) {
			ex.printStackTrace();
		} finally {
			if (input != null) {
				try {
					input.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return propValue;
	}

}
Now Look at the property file , how it looks

Also read : how to read user input in java 

Code Follow (Explanation):


  1. Basically we have first created new Maven project in eclipse .
  2. Created new folder called resource inside src/main/ and add new property file called app.property.
  3. Now , created new class file called App.java ( may be auto generated) , In that wee will  create the main method for execution.
  4. After that we have created a utility class , where we have write the logic of reading property file( see PropertyUtil.java) and it will give use the value of key we will pass for read.

0 comments:

Post a Comment