Reading data from Property files using java program - Selenium Tutorial

Properties files (.properties) are used to store GUI locators, elements and global fields like database configuration details in Selenium. In Java .properties files are mainly used for maintaining project configuration data, database configuration, project settings etc. Each parameter will be stored in .properties file as a pair of strings in key and value format. The program to read data from properties file using java selenium is given below.

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class ReadFileData {

 public static void main(String[] args)  {
 File file = new File(“D:/Dev/ReadData/src/datafile.properties”);
 
FileInputStream fileInput = null;
try {
fileInput = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Properties prop = new Properties();

//load properties file
try {
prop.load(fileInput);
} catch (IOException e) {
e.printStackTrace();
}

WebDriver driver = new FirefoxDriver();

driver.get(prop.getProperty(“URL”));
driver.findElement(By.id(“Email”)).sendKeys(prop.getProperty(“username”));
driver.findElement(By.id(“Passwd”)).sendKeys(prop.getProperty(“password”));
driver.findElement(By.id(“SignIn”)).click();

System.out.println(“URL ::” + prop.getProperty(“URL”));
System.out.println(“User name::” +prop.getProperty(“username”));
System.out.println(“Password::” +prop.getProperty(“password”));
 }
}

Output after the execution of the program is given below

URL ::

http://gmail.com

Username::testuser
Password::password123

The below-given Java program can be used to get all the key value pairs in properties file.

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;

public class ReadFileData {

public static void main(String[] args) {

File file = new File

(“D:/Dev/ReadData/src/datafile.properties”);
FileInputStream fileInput = null;
try {
fileInput = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Properties prop = new Properties();
try {
prop.load(fileInput);
} catch (IOException e) {
e.printStackTrace();
}

Enumeration KeyValues = prop.keys();
while (KeyValues.hasMoreElements()) {
String key = (String) KeyValues.nextElement();
String value = prop.getProperty(key);
System.out.println(key + “:- ” + value);
}
}
}

How to Create Properties File

Go to ‘file’ menu then click on ‘new’ and select ‘file’. Provide file name and then extension as ‘.properties’.

Leave a Reply

Your email address will not be published. Required fields are marked *