The Wayback Machine - https://web.archive.org/web/20240616163219/https://www.geeksforgeeks.org/reading-csv-file-java-using-opencsv/
Open In App

Reading a CSV file in Java using OpenCSV

Last Updated : 28 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

A Comma-Separated Values (CSV) file is just a normal plain-text file, store data in column by column, and split it by a separator (e.g normally it is a comma “, ”).

OpenCSV is a CSV parser library for Java. OpenCSV supports all the basic CSV-type operations you are want to do. Java 7 is currently the minimum supported version for OpenCSV. Java language does not provide any native support for effectively handling CSV files so we are using OpenCSV for handling CSV files in Java.

How to Use OpenCSV

1. For maven project, you can include the OpenCSV maven dependency in pom.xml file.

HTML




<dependency>
    <groupId>com.opencsv</groupId>
    <artifactId>opencsv</artifactId>
    <version>4.1</version>
</dependency>


2. For Gradle Project, you can include the OpenCSV dependency. 

compile group: 'com.opencsv', name: 'opencsv', version: '4.1'

3. You can Download OpenCSV Jar and include in your project class path.

Some useful classes of opencsv 

  1. CSVReader – This class provides the operations to read the CSV file as a list of String array.
  2. CSVWriter – This class allows us to write the data to a CSV file.
  3. CsvToBean – This class will be used when you want to populate your java beans from a CSV file content.
  4. BeanToCsv – This class helps to export data to CSV file from your java application.

Reading CSV File

For reading a CSV file you need CSVReader class. Following are sample CSV file that we’ll read.  

name, rollno, department, result, cgpa
amar, 42, cse, pass, 8.6
rohini, 21, ece, fail, 3.2
aman, 23, cse, pass, 8.9
rahul, 45, ee, fail, 4.6
pratik, 65, cse, pass, 7.2
raunak, 23, me, pass, 9.1
suvam, 68, me, pass, 8.2

We can read csv file by two ways : 

1. Read data line by line : Lets see how to read CSV file line by line. For reading data line by line, first we have to construct and initialize CSVReader object by passing the filereader object of CSV file. After that we have to call readNext() method of CSVReader object to read data line by line as shown in below code.

Java




// Java code to illustrate reading a
// CSV file line by line
public static void readDataLineByLine(String file)
{
  
    try {
  
        // Create an object of filereader
        // class with CSV file as a parameter.
        FileReader filereader = new FileReader(file);
  
        // create csvReader object passing
        // file reader as a parameter
        CSVReader csvReader = new CSVReader(filereader);
        String[] nextRecord;
  
        // we are going to read data line by line
        while ((nextRecord = csvReader.readNext()) != null) {
            for (String cell : nextRecord) {
                System.out.print(cell + "\t");
            }
            System.out.println();
        }
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}


2. Read all data at once : We read the CSV records one by one using the readNext() method. CSVReader also provides a method called readAll() to read all the records at once into a List.

 List allData = csvReader.readAll(); 

When we read csv file by default, header will not ignored, as shown in output of above codes. When we need to skip the first element in the list then we can specify start line while creating CSVReader. 

CSVReader csvReader = 
new CSVReaderBuilder(reader).withSkipLines(1).build();

Code: 

Java




// Java code to illustrate reading a
// all data at once
public static void readAllDataAtOnce(String file)
{
    try {
        // Create an object of file reader
        // class with CSV file as a parameter.
        FileReader filereader = new FileReader(file);
  
        // create csvReader object and skip first Line
        CSVReader csvReader = new CSVReaderBuilder(filereader)
                                  .withSkipLines(1)
                                  .build();
        List<String[]> allData = csvReader.readAll();
  
        // print Data
        for (String[] row : allData) {
            for (String cell : row) {
                System.out.print(cell + "\t");
            }
            System.out.println();
        }
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}


Reading CSV File with different separator

CSV files can be separated with a delimiter other than a comma e.g. semi-colon, pipe etc. The following example shows how to read data of CSV file separated by a semi-colon character. 

Semi-colon separated CSV file example :  

name;rollno;department;result;cgpa
amar;42;cse;pass;8.6
rohini;21;ece;fail;3.2
aman;23;cse;pass;8.9
rahul;45;ee;fail;4.6
pratik;65;cse;pass;7.2
raunak;23;me;pass;9.1
suvam;68;me;pass;8.2

For Custom separator first CSVParser with specific parser character is created. 

CSVParser parser = new CSVParserBuilder().withSeparator(';').build();

Then we will create CSVReader object withCSVParser() method along with constructor and provided the made parser object to parameter of withCSVParser method.At last call build method to build object. 

CSVReader csvReader = new CSVReaderBuilder(filereader).withCSVParser(parser).build();

Code:  

Java




// Java code to illustrate
// Reading CSV File with different separator
public static void readDataFromCustomSeparator(String file)
{
    try {
        // Create an object of file reader class with CSV file as a parameter.
        FileReader filereader = new FileReader(file);
  
        // create csvParser object with
        // custom separator semi-colon
        CSVParser parser = new CSVParserBuilder().withSeparator(';').build();
  
        // create csvReader object with parameter
        // filereader and parser
        CSVReader csvReader = new CSVReaderBuilder(filereader)
                                  .withCSVParser(parser)
                                  .build();
  
        // Read all data at once
        List<String[]> allData = csvReader.readAll();
  
        // Print Data.
        for (String[] row : allData) {
            for (String cell : row) {
                System.out.print(cell + "\t");
            }
            System.out.println();
        }
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}


Example – Reading two csv Files result.csv and results_semicolon_Separator.csv 
result.csv has default separator ‘, ‘ but results_semicolon_Separator.csv has a separator ‘;’ in place of ‘, ‘.

 Codes:

Java




// Java program to illustrate reading
// two CSV files
// with different separators
  
import java.io.FileReader;
import java.util.List;
import com.opencsv.*;
  
public class ReadCSVData {
    private static final String CSV_FILE_PATH
        = "D:\\EclipseWorkSpace\\CSVOperations\\results.csv";
    private static final String CSV_FILE_CUSTOM_SEPARATOR
        = "D:\\EclipseWorkSpace\\CSVOperations\\results_semicolon_Separator.csv";
  
    public static void main(String[] args)
    {
  
        System.out.println("Read Data Line by Line With Header \n");
        readDataLineByLine(CSV_FILE_PATH);
        System.out.println("_______________________________________________");
  
        System.out.println("Read All Data at Once and Hide the Header also \n");
        readAllDataAtOnce(CSV_FILE_PATH);
        System.out.println("_______________________________________________");
  
        System.out.println("Custom Separator here semi-colon\n");
        readDataFromCustomSeparator(CSV_FILE_CUSTOM_SEPARATOR);
        System.out.println("_______________________________________________");
    }
  
    public static void readDataLineByLine(String file)
    {
  
        try {
  
            // Create an object of filereader class
            // with CSV file as a parameter.
            FileReader filereader = new FileReader(file);
  
            // create csvReader object passing
            // filereader as parameter
            CSVReader csvReader = new CSVReader(filereader);
            String[] nextRecord;
  
            // we are going to read data line by line
            while ((nextRecord = csvReader.readNext()) != null) {
                for (String cell : nextRecord) {
                    System.out.print(cell + "\t");
                }
                System.out.println();
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
  
    public static void readAllDataAtOnce(String file)
    {
        try {
  
            // Create an object of filereader class
            // with CSV file as a parameter.
            FileReader filereader = new FileReader(file);
  
            // create csvReader object
            // and skip first Line
            CSVReader csvReader = new CSVReaderBuilder(filereader)
                                      .withSkipLines(1)
                                      .build();
            List<String[]> allData = csvReader.readAll();
  
            // print Data
            for (String[] row : allData) {
                for (String cell : row) {
                    System.out.print(cell + "\t");
                }
                System.out.println();
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
  
    public static void readDataFromCustomSeparator(String file)
    {
        try {
            // Create object of filereader
            // class with csv file as parameter.
            FileReader filereader = new FileReader(file);
  
            // create csvParser object with
            // custom separator semi-colon
            CSVParser parser = new CSVParserBuilder().withSeparator(';').build();
  
            // create csvReader object with
            // parameter filereader and parser
            CSVReader csvReader = new CSVReaderBuilder(filereader)
                                      .withCSVParser(parser)
                                      .build();
  
            // Read all data at once
            List<String[]> allData = csvReader.readAll();
  
            // print Data
            for (String[] row : allData) {
                for (String cell : row) {
                    System.out.print(cell + "\t");
                }
                System.out.println();
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}


Output: 

_______________________________________________
Read Data Line by Line With Header 

name    rollno    department    result    cgpa    
amar    42    cse    pass    8.6    
rohini    21    ece    fail    3.2    
aman    23    cse    pass    8.9    
rahul    45    ee    fail    4.6    
pratik    65    cse    pass    7.2    
raunak    23    me    pass    9.1    
suvam    68    me    pass    8.2    
_______________________________________________
Read All Data at Once and Hide the Header also 

amar    42    cse    pass    8.6    
rohini    21    ece    fail    3.2    
aman    23    cse    pass    8.9    
rahul    45    ee    fail    4.6    
pratik    65    cse    pass    7.2    
raunak    23    me    pass    9.1    
suvam    68    me    pass    8.2    
_______________________________________________
Custom Separator here semi-colon

name    rollno    department    result    cgpa    
amar    42    cse    pass    8.6    
rohini    21    ece    fail    3.2    
aman    23    cse    pass    8.9    
rahul    45    ee    fail    4.6    
pratik    65    cse    pass    7.2    
raunak    23    me    pass    9.1    
suvam    68    me    pass    8.2    
_______________________________________________

In future articles, we will include more Operations on CSV file using OpenCSV. 
References: CSVReader class Documentation, OpenCSV Documentation
 



Similar Reads

Writing a CSV file in Java using OpenCSV
A Comma-Separated Values (CSV) file is just a normal plain-text file, store data in a column by column, and split it by a separator (e.g normally it is a comma “, ”). OpenCSV is a CSV parser library for Java. OpenCSV supports all the basic CSV-type operations you are want to do. Java 7 is currently the minimum supported version for OpenCSV. Java la
5 min read
Mapping Java Beans to CSV Using OpenCSV
The need to convert Java Beans(Objects) to CSV file arises very commonly and there are many ways to write Bean into CSV file but one of the best ways to map java bean to CSV is by using OpenCSV Library. In OpenCSV there is a class name StatefulBeanToCsvBuilder which helps to convert Java Beans to CSV. The first task is to add the OpenCSV library in
4 min read
Mapping CSV to JavaBeans Using OpenCSV
OpenCSV provides classes to map CSV file to a list of Java-beans. CsvToBean class is used to map CSV data to JavaBeans. The CSV data can be parsed to a bean, but what is required to be done is to define the mapping strategy and pass the strategy to CsvToBean to parse the data into a bean. HeaderColumnNameTranslateMappingStrategy is the mapping stra
4 min read
Reading and Writing Data to Excel File in Java using Apache POI
In Java, reading an Excel file is not similar to reading a Word file because of cells in an Excel file. JDK does not provide a direct API to read data from Excel files for which we have to toggle to a third-party library that is Apache POI. Apache POI is an open-source java library designed for reading and writing Microsoft documents in order to cr
5 min read
How to Write JSON Array to CSV File using Java?
We will see how to read a JSONArray from a JSON file and write the contents to a CSV file using Java. JavaScript Object Notation (JSON) is a standard text-based format for representing structured data that is based on JavaScript object syntax. It is commonly used for transmitting data in web applications (e.g., sending some data from the server to
3 min read
How to Extract Email Addresses, Phone Numbers from a CSV File using Java?
CSV stands for Comma Separated Values. A CSV file is a plain text file. CSV file is used to store the records. CSV File records are stored with delimiter separator value. Problem Statement A CSV file is given. The task is to read and extract phone numbers, and email ids from the given CSV file, and return the list of phone numbers and emails as out
2 min read
Reading Text File into Java HashMap
We will look into the Method that allows us to read the HashMap Text from the file or how we can De-serialised the File De-Serialization: Here we are reproducing the HashMap object and it’s content from a serialized file. Approach: Firstly the method/Function HashMapFromTextFile will have the Method bufferedReader which read the Line of the text Fi
2 min read
Reading and Writing Properties File in Java
The property file is a file we use in the Java Programming language to keep the configuration parameters. These files we called Resource Bundle because it is a bundle of resources that we are going to use in the application. What are the configuration parameters? Configuration parameters are the parameters that you use at the time of configuring yo
4 min read
Different ways of Reading a text file in Java
There are multiple ways of writing and reading a text file in Java. this is required while dealing with many applications. There are several ways to read a plain text file in Java e.g. you can use FileReader, BufferedReader, or Scanner to read a text file. Every utility provides something special e.g. BufferedReader provides buffering of data for f
6 min read
How to Plot a Graph in Android Using CSV File?
When we are dealing with large amounts of data sets and if we want to display the data graphically then it becomes sometimes tough to generate a graph using that data so in this article we are going to implement this in an easy manner and you can add any types of graph and charts like BarChart, PieChart and many more. CSV File that we are going to
5 min read
Article Tags :
Practice Tags :