Java - Reading from a CSV File

CSV stands for Comma Separated Values.

A CSV file is a normal plain text file that stores data in columns, with a separator (by default comma) between the columns.

In this tutorial, let's learn how to handle CSV files in a Java Spring Boot application.

OpenCSV Library

The OpenCSV is one of the commonly used CSV parser libraries available for Java.

In order to use OpenCSV library, the application needs Java 7 or above.

Add OpenCSV Library to a Java Project

For maven projects, add the below dependency in the pom.xml file.

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

For gradle projects, add the below dependency.

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

Or, download the JAR file and include it in the project classpath.

Download OpenCSV JAR

Reading from a CSV file

To read content from a CSV file, we need to create an instance of CSVReader by providing FileReader object as shown below.

  • Before reading data, create an instance of CSVReader by providing FileReader object as shown below.
  • Use the method readNext() to read data line by line, where each record read is in the form of a strings array.
  • Use the method readAll() to read data all the lines at once, where the records read is in the form of a list of strings array.
  • By default, the column separator is a comma, which can be changed while configuring CSVReader.

NOTE: If the CSV file doesn't exist at the path specified, then the file is created, otherwise the content of the existing file is updated.

Sample Data

Let's assume the below data in the CSV file, where the separator is a comma (the default separator).

ID,Name,Class,Marks
1,Arun,10,520
2,Sravan,10,630
3,Kiran,10,580

1. Reading from a CSV file line by line

public static void readDataLineByLine() {
    // specifying the CSV file path
    String filePath = "/files/sample.csv";

    // creating File object with the file location specified
    File file = new File(filePath);

    try {
        // creating FileReader object with file as parameter
        FileReader fileReader = new FileReader(file);

        // creating CSVReader object using FileReader object
        CSVReader csvReader = new CSVReader(fileReader);

        // reader data line by line
        String[] record;
        while(record = csvReader.readNext() != null){
            for(String cell : record){
                System.out.print(cell + "\t");
            }
            System.out.println();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

2. Reading from a CSV file all lines at once

public static void readDataAllLinesAtOnce() {
    // specifying the CSV file path
    String filePath = "/files/sample.csv";

    // creating File object with the file location specified
    File file = new File(filePath);

    try {
        // creating FileReader object with file as parameter
        FileReader fileReader = new FileReader(file);

        // creating CSVReader object using FileReader object
        CSVReader csvReader = new CSVReader(fileReader);

        // creating the list (containing both header and data) using String array
        List<String[]> data = csvReader.readAll();

        // printing data
        for(String[] row : data){
            for(String cell : row){
                System.out.print(cell + "\");
            }
            System.out.println();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

3. Reading from a CSV file with a custom separator

By default, the separator is a comma (,) which can be changed by providing the custom separator as a parameter to CSVReader constructor as shown below.

Here is the implementation to read data using a custom separator.

// creating FileReader object with file as parameter
FileReader fileReader = new FileReader(file);

// Construct CSVParser with the required separator
CSVParser parser = new CSVParserBuilder().withSeparator('|').build();

// Build CSVReader using the parser
CSVReader csvReader = new CSVReaderBuilder(fileReader).withCSVParser(parser).build();

4. Reading from a CSV file skipping header row

By default, the CSVReader reads all the rows including the header, and it can be changed by adding additional configuration using withSkipLines() as shown below.

Here is the implementation to skip the header line.

// creating FileReader object with file as parameter
FileReader fileReader = new FileReader(file);

// Build CSVReader using the parser
CSVReader csvReader = new CSVReaderBuilder(fileReader).withSkipLines(1).build();

Conclusion

Now, we know how to read data from a CSV file in a Spring Boot application using the opencsv library.

Related Links

  • Writing data to a CSV file
  • Reading data from a CSV file
  • Mapping data from a CSV file to Java beans
  • Mapping data from Java beans to a CSV file

References

For more details about the OpenCSV library, refer to the official documentation in the below links.