Basic Selenium

How to read CSV files using Java

Hello Welcome to Selenium Tutorial, in this post How to read CSV files using Java and how we can use into our Selenium script.

Selenium support only browser level automation and it does not have any API to read and write external data like Excel, Database   so in previous post we have seen JExcel API and Apache POI.

What is CSV files.
CSV stands for comma separated values. Sometimes in your application you have to take data from existing csv files as well. Here is how csv files looks.

Read csv files

Read csv files

How to create CSV files

Open Notepad Enter Some values in format mention below and Save file as  .csv format

“Automation”,”Selenium”,”Webdriver”
“Testing”,”Selenium”,”RC”

After saving files looks like

How to read CSV files using Java

How to read CSV files using Java

How to read CSV files

In this post we will use some third party API called opencsv, we can download this as jar file and can use existing methods to read file

download opencsv using below link

http://www.java2s.com/Code/Jar/o/Downloadopencsv23jar.htm

How to read CSV files using Java

How to read CSV files using Java

This will come as rar file extract this then you will find jar

Add that jar into project

How to add jar -Right click on project > Select Build path > Select configure build path> Add external jar> now Select the jar which we downloaded

Steps How to read-

1- We have predefined class called CSVReader, create an object and pass the csv file path

2- call readAll() method which will return the csv content in List<String[]>

3-using Iterator, you can iterate all the values and use according to application

Program – How to read CSV files using Java

package blog;
import java.io.FileReader;
import java.util.Iterator;
import java.util.List;

import au.com.bytecode.opencsv.CSVReader;

public class ReadCsvFiles {

 public static void main(String[] args) throws Exception {
    
 // This will load csv file 
 CSVReader reader = new CSVReader(new FileReader("C:\\Users\\mukesh_otwani\\Desktop\\demo.csv"));

 // this will load content into list
  List<String[]> li=reader.readAll();
  System.out.println("Total rows which we have is "+li.size());
            
 // create Iterator reference
  Iterator<String[]>i1= li.iterator();
    
 // Iterate all values 
 while(i1.hasNext()){
     
 String[] str=i1.next();
   
 System.out.print(" Values are ");

 for(int i=0;i<str.length;i++)
{

   System.out.print(" "+str[i]);

}
   System.out.println("   ");
     
    
}

}

}

 

Thanks for visiting my blog, Please comment below if you finding any issue while reading files.

Keep in touch. Have a nice day 🙂

 

 

author-avatar

About Mukesh Otwani

I am Mukesh Otwani working professional in a beautiful city Bangalore India. I completed by BE from RGPV university Bhopal. I have passion towards automation testing since couple of years I started with Selenium then I got chance to work with other tools like Maven, Ant, Git, GitHub, Jenkins, Sikuli, Selenium Builder etc.

28 thoughts on “How to read CSV files using Java

  1. Devisha Mishra says:

    Thanks it really helped me!!!

    1. Thanks Devisha, I am glad it helped.

  2. Hema says:

    Does apache POI support CSV files??

    1. Hi Hema,

      You may need to used Apache Commons CSV library for same

      1. Hema says:

        Do you have any video for reading .csv file ??

        1. Hi Hema,

          Check this link. Hoppe this will help you.

  3. Manju says:

    Mukesh,

    Hope you are doing well..
    I have a quick question, I have designed page object factory framework. when we pass the argument in the main method for created method, do we have the possibility to pass the argument value using text file .The main idea is here not to pass the username ,password and other value in the in the main method.

    1. Hi Manju,

      I would recommend you to use properties/xml/json file instead of text file to read these kinds of data in your testing. You can have some file reader class to handle files to read data

  4. Varun says:

    It helped me.Thanks!

    1. Hi Varun,

      You’re most welcome…:)

  5. Lakshmi says:

    How to search for a string and get the next element value in csv file

    1. Hi Lakshmi,

      As mentioned in blog post, iterate all List elements. While iteration, check for required string and whenever condition gets satisfied, iterate once more and break loop.

  6. reddi says:

    HI makes i had an issue with mac os using visual studio can u pls how to work on this using C# rather than java
    thanks in advance

    1. Hi Reddi,

      Extremely sorry, I never worked with C# for selenium. If it is Java then I can surely help you. You are always welcome to learn-automation.com

  7. prasad says:

    hi mukesh can u show how the data will call from csv file to fill the registration forms(like registring a user in to any application gmail,facebook)

  8. harvir says:

    hi Mukesh,
    is there any way to read data from csv file like excel file, based on column and row index
    ?? plz let me know if there is any way

    1. Hi Harvir,

      Yes you can do that but for that you have to write your own code.

  9. Ranjith Samalla says:

    HI Mukesh,

    Gud evng,

    What is use of csv file, In real time project where we can use, it is rerally important to learn.can u expn clearly.

    1. Hey Ranjith,

      It depends on org some companies use excel to read data and some use csv file 🙂

  10. Akshay Tale says:

    Hi,

    Why we are introducing complexity of external jar here? We can directly read this file line by line as CSV is normal text file and then use StringTokenizer class (inbuilt in Java) to split every line with comma(,) as delimiter and use individual elements as cells of excel.

    1. Hi Akshay,

      You can do using pure java code as well. I showed using OpenCSV jars.

  11. Vamshi Guddeti says:

    Can you show a simple program for us to move the csv file parameters to constructor..!!

    1. Hey Vamshi,

      I applied the same concept in reading excel file post. Kindly check and try to apply the same logic.

  12. Amit says:

    Thumbs up for ur presentation : )

    ” List li=reader.readAll();”

    Why we are using list here since we can directly store in a string array?

    1. Hi Amit,

      It all depends on return type of method. List is part of collection interface and it allow dynamic element to be stored.

  13. Naga says:

    Where is the au.com.bytecode.opencsv.CSVReader??

    1. Hi Naga,

      It is coming from the jar which we have to download..

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.