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 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");

PropertyUtil Class Code:

package com.programinjava.learn.ReadPropertyFileDemo;

import java.util.Properties;

public class PropertyUtil {
//	define the path of property file 
private static final String PROPERTY_FILE_PATH="src/main/resources/";	
	public static String readProperty(String propName) {
		Properties prop = new Properties();
		InputStream input = null;
		String propValue = null;
		try {
			input = new FileInputStream(PROPERTY_FILE_PATH);
			propValue = prop.getProperty(propName);
		} catch (IOException ex) {
		} finally {
			if (input != null) {
				try {
				} catch (IOException e) {
		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
  3. Now , created new class file called ( 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 and it will give use the value of key we will pass for read.


Post a Comment