Skip to content
Related Articles

Related Articles

Improve Article

Reading a CSV file in Java using OpenCSV

  • Difficulty Level : Medium
  • Last Updated : 29 Jul, 2021
Geek Week

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
 

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :