Automation Reading Properties File
Reading Properties File
In automation, the most common thing in almost all frameworks is to read and write configuration parameters from the properties file. In this post, we will learn steps to read properties file in Java.
Let’s assume the file name “config.properties” and the class named “ConfigHelper” . Now we will see how to add a constructor to the class. A constructor is a method that is called when the object is created.
Every class in java has a default constructor even if we don’t specify it in the class code. Constructor method name should be the same as the class name as shown below:
public ConfigHelper(String configFileName) { this.configFileName = configFileName; }
We can create an instance of properties class as:
Properties properties = new Properties();
We will write 3 methods in the class : to set property, get property , remove property .
Properties file would have key value pairs . Below is a sample config values :
RunLocal=TRUE AppUrl=https://www.bing.com UserName=sampleUsername Password=sampleFfgfgTYYhfhgh1234nfnfFFSSSRR
How to get the property
Below is the method to get the property
public String getProperty(String strKey) { try { File f = new File(configFileName); if (f.exists()) { FileInputStream in = new FileInputStream(f); properties.load(in); propValue = properties.getProperty(strKey); in.close(); } else System.out.println("File not found!"); } catch (Exception e) { System.out.println(e); } return propValue; }
How to set the property
public void setProperty(String mpropKey, String mpropValue) throws Throwable { try { File f = new File(configFileName); if (f.exists()) { FileInputStream in = new FileInputStream(f); properties.load(in); properties.setProperty(mpropKey, mpropValue); properties.store(new FileOutputStream(configFileName), null); in.close(); } else { System.out.println("File not found!"); } } catch (Exception e) { System.out.println(e); } }
How to remove the property
public void removeProperty(String mpropKey) { try { File f = new File(configFileName); if (f.exists()) { FileInputStream in = new FileInputStream(f); properties.load(in); properties.remove(mpropKey); properties.store(new FileOutputStream(configFileName), null); in.close(); } else System.out.println("File not found!"); } catch (Exception e) { System.out.println(e); } }
To instantiate we can call this class like below:
ConfigHelper config = new ConfigHelper("config.properties");
For example to read username, e do this like the below snippet:
String USERNAME = config.getProperty("UserName");