A Comma Separated Values (CSV) file is a simple text file that stores data in a tabular format, where columns are separated by a delimiter (usually a comma or a tab). These files are typically used for importing and exporting data between servers and applications.

In my previous articles, I wrote about reading and write CSV files using core Java, OpenCSV, Apache Common CSV, and Spring Boot.

In this article, we shall look at different ways to read and parse a CSV file in Java.

Here is an example of a simple CSV file that uses a comma (,) as a delimiter to separate column values and doesn't contain any double-quote:

users.csv

1,John Doe,john@example.com,AE
2,Alex Jones,alex@example.com,DE
3,Jovan Lee,jovan@example.com,FR
4,Greg Hover,greg@example.com,US

Read CSV File using Core Java

To read and parse a simple CSV like the above that doesn't contain the delimiter inside column values, core Java classes can be used. You can either use the BufferedReader class or the Scanner class to easily read the file in Java.

BufferedReader Class

Since CSV is just a plain-text file, the BufferedReader class can be used to read it line by line. You can then use the String.split() method to split each line by comma to convert it into columns. Here is an example:

// create a reader
try (BufferedReader br = Files.newBufferedReader(Paths.get("users.csv"))) {

    // CSV file delimiter
    String DELIMITER = ",";

    // read the file line by line
    String line;
    while ((line = br.readLine()) != null) {

        // convert line into columns
        String[] columns = line.split(DELIMITER);

        // print all columns
        System.out.println("User["+ String.join(", ", columns) +"]");
    }

} catch (IOException ex) {
    ex.printStackTrace();
}

Here is what the output looks like:

User[1, John Doe, john@example.com, AE]
User[2, Alex Jones, alex@example.com, DE]
User[3, Jovan Lee, jovan@example.com, FR]
User[4, Greg Hover, greg@example.com, US]

Scanner Class

Another way of reading and parsing a CSV file in core Java is using the Scanner class. This class converts its input into tokens using a delimiter pattern. The resulting tokens may then be converted into values of different types using different next() methods.

Here is an example that shows how you can use Scanner to read and parse a CSV file:

// create scanner instance
try (Scanner scanner = new Scanner(Paths.get("users.csv").toFile())) {

    // CSV file delimiter
    String DELIMITER = ",";

    // set comma as delimiter
    scanner.useDelimiter(DELIMITER);

    // read all fields
    while (scanner.hasNext()) {
        System.out.print(scanner.next() + " ");
    }

} catch (IOException ex) {
    ex.printStackTrace();
}

The above code will output the following on the console:

1 John Doe john@example.com AE
2 Alex Jones alex@example.com DE
3 Jovan Lee jovan@example.com FR
4 Greg Hover greg@example.com US

Check out the Reading and Writing CSV files using core Java tutorial for more examples.

Read CSV File using OpenCSV

OpenCSV is a popular library for reading, writing, parsing, serializing, and deserializing CSV files in Java. This library is a good choice for handling different CSV formats, delimiters, and special characters.

To add OpenCSV support to your Gradle project, add the following dependency to the build.gradle file:

implementation 'com.opencsv:opencsv:5.0'

For Maven, add the below dependency to your pom.xml file:

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

The following example demonstrates how you can read and parse a CSV file named users.csv using OpenCSV:

// create a csv reader
try (Reader reader = Files.newBufferedReader(Paths.get("users.csv"));
     CSVReader csvReader = new CSVReader(reader)) {

    // read one record at a time
    String[] record;
    while ((record = csvReader.readNext()) != null) {
        System.out.println("User["+ String.join(", ", record) +"]");
    }

} catch (IOException | CsvValidationException ex) {
    ex.printStackTrace();
}

The above example will output the following on the console:

User[1, John Doe, john@example.com, AE]
User[2, Alex Jones, alex@example.com, DE]
User[3, Jovan Lee, jovan@example.com, FR]
User[4, Greg Hover, greg@example.com, US]

Check out OpenCSV tutorial to dig deeper and learn more about OpenCSV.

Read CSV File using Apache Commons CSV

Apache Commons CSV is another 3rd-party library for reading and parsing CSV files in Java. It provides several ways to read CSV files in different formats.

For a Gradle project, add the following dependency to the build.gradle file to import Commons CSV:

implementation 'org.apache.commons:commons-csv:1.7'

For Maven, add the below dependency to your pom.xml file:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-csv</artifactId>
    <version>1.7</version>
</dependency>

Here is an example that shows how you can use the Apache Commons CSV library to read and parse the contents of a CSV file in Java:

// create a reader
try (Reader reader = Files.newBufferedReader(Paths.get("users.csv"))) {

    // read csv file
    Iterable<CSVRecord> records = CSVFormat.DEFAULT.parse(reader);
    for (CSVRecord record : records) {
        System.out.println("Record #: " + record.getRecordNumber());
        System.out.println("ID: " + record.get(0));
        System.out.println("Name: " + record.get(1));
        System.out.println("Email: " + record.get(2));
        System.out.println("Country: " + record.get(3));
    }

} catch (IOException ex) {
    ex.printStackTrace();
}

The above example will print the following on the console:

Record #: 1
ID: 1
Name: John Doe
Email: john@example.com
Country: AE
Record #: 2
ID: 2
Name: Alex Jones
Email: alex@example.com
Country: DE
Record #: 3
ID: 3
Name: Jovan Lee
Email: jovan@example.com
Country: FR
Record #: 4
ID: 4
Name: Greg Hover
Email: greg@example.com
Country: US

Check out Apache Commons CSV tutorial for a deeper understanding of how It works and how you can use it to read and write different CSV formats.

Conclusion

That's all for reading and parsing a CSV file in Java. We talked about different ways of reading and parsing a CSV file, including core Java and 3rd-party libraries like OpenCSV and Apache Commons CSV.

For simple CSV file formats where column values do not contain the delimiter itself, core Java is a good choice.

For more complex CSV file formats, you should rely on a 3rd-party library like OpenCSV or Apache Commons CSV for correctly parsing the data. Personally, I prefer to use OpenCSV because it supports multiple CSV formats, special characters, and more.

If you want to create and download a CSV file in a Spring Boot application, check out this excellent tutorial I wrote a while ago.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.