Tuesday 6 March 2018

How to Read data from CSV file in Selenium

Read test data from any external source in selenium is very important when we are working with framework. Test data can be store in any format like excel, CSV, text etc.

In this article, we will discuss how we can read data from CSV file.

CSV file is comma separated Value file. It means all the value in file is comma separated from each other. If we want to read data from CSV file then we need to first get all comma separated values individually.

I have created one function for read data from CSV first and store it to two dimensional string array.

Lets take an example. Suppose we have below CSV file.



You can see here in every line all values are comma separated. 

I have created below function for read data from CSV file.


 public String[][] GetDataFromCSV(File fCSVFile)
 {  
        List<String[]> resultsList = new ArrayList<String[]>();
  try
  {
   BufferedReader reader = new BufferedReader(new FileReader(fCSVFile.getAbsolutePath()));
         String line;
         while((line = reader.readLine()) != null)
         {
          String[] temp = line.split(",");          
          resultsList.add(temp);
         }         
         reader.close();
  }
  catch (Exception e) 
  {
   e.printStackTrace();
  }
    
  String[][] resultsArray = new String[resultsList.size()][resultsList.get(0).length];
  
  for(int i=0; i<resultsList.size(); i++)
        {
         for(int j=0; j<resultsList.get(0).length; j++)
         {
          resultsArray[i][j] = resultsList.get(i)[j];
         }
        }
  
  return resultsArray;
 }

Code Explanation : 

In above code, you can see first I am reading every line and spit line by ','. So I will get all values from every line.

String[] temp = line.split(",");

Once I get values from single line then I am storing that all values into List of one dimensional String array.

List<String[]> resultsList = new ArrayList<String[]>();
resultsList.add(temp);

After getting values from all the line, I am storing that values from List to two dimensional String array because we want  data from CSV into two dimensional String array.

String[][] resultsArray = new String[resultsList.size()][resultsList.get(0).length];

for(int i=0; i<resultsList.size(); i++)
        {
        for(int j=0; j<resultsList.get(0).length; j++)
        {
        resultsArray[i][j] = resultsList.get(i)[j];
        }

        }

Please add comment if you have any question.


Popular