Reading Properties file using Java
What is properties file?
- Properties file is a simple collection of key-value pairs data.
- Properties files are widely used for many purposes in all kinds of java applications, often to store configuration or localization data.
How to create file?
- User can save the normal text file with .properties extension instead of file.
Where we use properties file
- In well-developed framework, has to provide some details like type of browser, application url, , environment ) before trigger the automation suite.
- For easy maintenance and manipulations of configuration details, user have to use file (it will store in Key-Value pair combination).
Example :
Create file with name as “configurations.properties and add below two lines in it.
browserName=Firefox
ApplicationUrl=http://www.gmail.com
In above example, “browserName” is a Key and “Firefox” is the Value (assigned to Key) "ApplicationUrl" is a Key and “http://www.gmail.com” is the Value(assigned to Key ApplicationUrl)Let us see how to read file data using Java:
FileInputStream fInput= new FileInputStream(new File(“Path of the .properties file”)); Properties configProps=new Properties();//Predefined class in java configProps.load(fInput); System.out.println(“Value assigned to ‘browserName’ key is :”+configProps.getProperty(“browserName”)); System.out.println(“Value assigned to ‘ApplicationUrl’ key is :”+configProps.getProperty(“ApplicationUrl”));Now, please change value from “Firefox” to “Chrome” in file and again re-run the program. Note: Duplicate key will are not in properties fileKey name should be unique. User cannot give browserName=Firefox browserName=Chrome at time in same file.