How to Read Data From Properties File in Java

In this article we learn the how to read data from properties file in java. A file with extension .properties in java is called a property file which stores the data in form of key value pair. We can store our locators in a properties file, and we can read it from properties file and we can use to create object repository. Properties files are mainly used in Java programs to maintain project configuration data, database configurations or project settings etc.

How to read data from properties file in java?

Step 1: Create a file with extension .properties as “Config. properties”.

Create properties file-> Navigate to File menu -> New -> Click on File ->The only thing we need to do is, give the file name and give the extension as ‘.properties’ (Example: The below is the sample properties file that was used for tests. White space between the property name and property value is always ignored





Step 2: Load the properties file using load () method of Properties class.

FileInputStream fis = new FileInputStream (“Path of File”);

FileInputStream ->Java FileInputStream class obtains input bytes from a file. It is used for reading byte-oriented data.

If File is not present in default project root location, we will get an exception like, FileNotFoundException, we have to provide a fully qualified path of the file as well.

Properties prop=new Properties ();

The java. util. Properties class is a class which represents a persistent set of properties.

The Properties can be saved to a stream or loaded from a stream.

Each key and its corresponding value in the property list is a string.

prop. load(fis);  //Load method used for linking file with properties

The program uses load () method to retrieve the list. When the program executes, it first tries to load the list from a file. If this file exists, the list is loaded else IO exception is thrown.

Step 3: Use get Property (String key) to read value using Key.

String Value=prop.getProperty(key); 

System.out.println(key +” : “+Value);

Searches for the property with the specified key in this property list.

If the key is not found in this property list, the default property list, and its defaults, recursively, are then checked. The method returns null if the property is not found.

Other Popular Articles

How to Read Data From Excel File in Selenium? 

Leave a Comment