Read and Parse CSV Content from a String in Java using Apache Commons CSV

Tags: Apache Commons Apache Commons CSV CSVRecord CSVParser CSVFormat CSV

In this tutorial, we are going to learn how to read and parse CSV content from a Java String using Apache Commons CSV library.

Add Apache Commons CSV library to your Java project

To use Apache Commons CSV Java library in the Gradle build project, add the following dependency into the build.gradle file.

compile group: 'org.apache.commons', name: 'commons-csv', version: '1.8'

To use Apache Commons CSV Java library in the Maven build project, add the following dependency into the pom.xml file.

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

To download the Apache Commons CSV jar file you can visit Apache Commons CSV download page at commons.apache.org

Read CSV String using CSVParser.parse() method

In the following Java code example, we use CSVParser.parse() static method to create CSVParser object in order to read CSV content from a given String.

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;

import java.io.IOException;

public class ParseCsvStringExample {
    public static void main(String... args) {
        String csvContent = "First Name,Last Name,Email,Phone Number\n" +
                "John,Doe,john@simplesolution.dev,123-456-789\n" +
                "Emerson,Wilks,emerson@simplesolution.dev,123-456-788\n" +
                "Wade,Savage,wade@simplesolution.dev,123-456-787\n" +
                "Star,Lott,star@simplesolution.dev,123-456-786\n" +
                "Claudia,James,claudia@simplesolution.dev,123-456-785\n";

        CSVFormat csvFormat = CSVFormat.DEFAULT.withFirstRecordAsHeader().withIgnoreHeaderCase();

        try(CSVParser csvParser = CSVParser.parse(csvContent, csvFormat)) {
            for(CSVRecord csvRecord : csvParser) {
                String firstName = csvRecord.get("First Name");
                String lastName = csvRecord.get("Last Name");
                String email = csvRecord.get("Email");
                String phoneNumber = csvRecord.get("Phone Number");

                System.out.println(firstName + "," + lastName + "," + email + "," + phoneNumber);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
The output is:
John,Doe,john@simplesolution.dev,123-456-789
Emerson,Wilks,emerson@simplesolution.dev,123-456-788
Wade,Savage,wade@simplesolution.dev,123-456-787
Star,Lott,star@simplesolution.dev,123-456-786
Claudia,James,claudia@simplesolution.dev,123-456-785

Happy Coding 😊

Write and Read CSV File in Java using Apache Commons CSV

Top 3 Libraries for Writing and Reading CSV File in Java

Spring Boot Web Application Download CSV File

Escape or Unescape String for CSV column data in Java using Apache Commons Text