How to create and read file in java for Selenium

What is the 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 file name 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= Ajay

age= 23


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. First we have to create object of Properties class.

Properties prop=new Properties(); // This class is available in java

3. 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?);

4. 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/;


5. Now, 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? (System.out.println(prop.getProperty(?Name?))) instead of ?name?, it will print null in console, as ?Name? is undefined.

– Also, 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.

– Now in future, if your browser is firefox, you just need to update your properties file, instead of editing the class files/ test-scripts. Avoid to make changes in script. Nothing should be hard-coded at test-script level.

No Responses

Write a response