Reading a CSV file in Java using OpenCV

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.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

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

    chevron_right

    
    

  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.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // 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();
        }
    }

    chevron_right

    
    

  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:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // 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();
        }
    }

    chevron_right

    
    

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 constrctor 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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java code to illustrate
// Reading CSV File with different separator
public static void readDataFromCustomSeperator(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 seperator 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();
    }
}

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to illustrate reading
// two CSV files
// with different seperators
  
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_SEPERATOR
        = "D:\\EclipseWorkSpace\\CSVOperations\\results_semicolon_Seperator.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 Seperator here semi-colon\n");
        readDataFromCustomSeperator(CSV_FILE_CUSTOM_SEPERATOR);
        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 readDataFromCustomSeperator(String file)
    {
        try {
            // Create object of filereader
            // class with csv file as parameter.
            FileReader filereader = new FileReader(file);
  
            // create csvParser object with
            // custom seperator 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();
        }
    }
}

chevron_right


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 Seperator 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



My Personal Notes arrow_drop_up

I am a Developer I love to code and bring my ideas alive

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


2


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.