Read properties file in Java Project




In this post, you will learn how to read properties file in Java project.

Introduction


  • In Java property file is a special file, which contains key-value pairs.
  • Java has provided Properties class in java.util package, which provides a way to read the property file values.

Step 1 – Create a property file


Inside the Java project, create a file app.properties inside the src folder. You can give any name to the file but property file should have a extension .properties. Open the file and add the following contents

app.name=Read properties file
app.version=1.0

As you can see, the file contains two properties app.name and app.version

Step 2 – Create a Java file


Inside the src folder, create a java file ReadProperties.java and add the following content

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

public class ReadProperties {
	public static void main(String[] args) throws IOException{
		
		String filePath = "C:\\Users\\bushan\\Documents\\workspace-sts-3.9.10.RELEASE\\Java-tutorial\\src\\app.properties";
		
		Properties prop = new Properties();
		
		FileInputStream fs = new FileInputStream(filePath);
		
		prop.load(fs);
		System.out.println(prop.getProperty("app.name"));
		System.out.println(prop.getProperty("app.version"));
	}
}

First, we are creating an object of Properties class

Properties prop = new Properties();

Next, we are creating an object of FileInputStream class to read the file

FileInputStream fs = new FileInputStream(filePath);

Next, we are loading the file using load() of Properties class

prop.load(fs);

Once we load the property file, then we can read the property values using getProperty(), this takes property name as a parameter.

System.out.println(prop.getProperty("app.name"));




Bushan Sirgur

Hey guys, I am Bushan Sirgur from Banglore, India. Currently, I am working as an Associate project in an IT company.

Leave a Reply