How to Read Data From Properties File in Java
In this blog, we will see How to Read Data From Properties File in Java. This will be asked in the most of the interview questions.
Things to Remember:
- Mostly, the properties file is used to maintain the configurable parameters of the project.
- Extension for this file is “.properties”
- Properties file data will be in a Key and Value pair format.
- whenever you’re creating a properties file, maintain the keys in unique format. Don’t use the existing key for your new value.
- If you use the existing key again, then whenever control searches for that key it will return the last searched value. This might leads to conflicts.
#CONFIG File username = Username password = pass firstname = fname
In the below snippet, we have done the following to Read Data from properties file:
- Created a new folder under our project and created a new properties file with some data
- Created a object and assigned the file location of this newly created properties file using FileInputStream class.
- Created a object for the Properties class.
- Loaded all the properties of our file using Properties.load() method.
- Using .getProperty() method, we can load all our data using Key as a parameter.
- Then, it prints the corresponding value of that key.
package Javaprograms; import java.io.FileInputStream; import java.util.Properties; public class ReadDataFromPropertiesFile { public static void main(String[] args) throws Exception { FileInputStream fis = new FileInputStream("E:/Selenium/SeleniumPrgrms/resources/config.properties"); Properties prop = new Properties(); prop.load(fis); String user = prop.getProperty("username"); String pword = prop.getProperty("password"); String fname = prop.getProperty("firstname"); System.out.println(user); System.out.println(pword); System.out.println(fname); } }
Output: -------- username = Username password = pass firstname = fname
Please watch the Youtube video for better understanding.