Skip to main content
  1. Articles/

Create and Read file in Java for Selenium

·3 mins


Use of file in Selenium #

  1. Properties are used to externalize the data which is configurable and if you put that data in your code (test script) you have to build the code each time you want to change the value of the property. The main advantage of properties is that they are outside your source code and you can change them anytime.
  2. Each parameter is stored as a pair of strings, one storing the name of the parameter (called the key), and the other storing the value.
  3. Whatever constant and generic entities are there in our project, we can define in file

How to create file #

  1. Open eclipse. Right click on the project, select New -> File -> Give filename as “” -> Finish. We cannot write java code in this. It is simple text file. Make sure to use extension as “properties” and not “property”.
  2. Write the following content in properties file in key: value pair format:
name = Katy 
age = 26
url =
browser= chrome

How to read file #

  1. Create a java class named inside the same project where file is created -> include “public static main” method and Finish
  2. Now we have to create object of Properties class.
Properties prop=new Properties(); // This class is available in java
  1. Create object of FileInputStream and give property file location as fileInputStream parameter (which property file is to be read)
FileInputStream ip= new FileInputStream(“location of property file”);
  1. Now we have to load the property file. Use properties object to load property file
prop.load(“fileInputStream object”)

Final code should look something like this:

Properties prop=new Properties();
FileInputStream ip= new FileInputStream(“home/username/PrjtName/src/”);
  1. Once the config file is loaded, we need to read the properties of config file. Properties object gives us a .getProperty method which takes the key of the property as a parameter and return the value of the matched key from the .properties file.
  • Make sure you use the same key as mentioned in properties file. This is case sensitive.
  • If you use “Name” instead of “name”, it will print null in console, as “Name” is undefined
  • If you comment “name” property by typing “#” in front of it in file and try to print “name” property System.out.println(prop.getProperty(“name”)), it will print null, as “name” is commented in properties file and hence cannot be accessed.
  • In future if your browser is firefox, you just need to update your properties file, instead of editing the class files/ test-scripts. Avoid making changes in script. Nothing should be hard-coded at test-script level.