0

Parse CSV file using Apache Commons CSV

Why use CSV files?

Sometimes we process data in bulk by reading them from files with specific format like CSV. This article demonstrates how to parse a CSV file using Apache Commons CSV. A CSV is a file format wherein values are comma-separated. Thus, CSV or comma-separated values.

Sample CSV file to read

To keep things really simple, we’ll use a small CSV file with 4 headers and 4 rows. The first row contains the header name for each column.

View CSV file using LibreOffice Calc

Here is the content of our CSV file using LibreOffice Calc

commons-csv-2015-12-08_232455

View CSV file using text editor

Here is the content of our CSV file using any text editor. In this case, we used gedit.

commons-csv-screenshot_from_2015-12-08_232538

The Codes

The following codes is from a class with only this method. Since we have headers, we need to use .withHeader() on CSVFormat.EXCEL to use the parse(Reader) method.

Download the Codes

https://github.com/Turreta/java-apache-commons-csv-example

We are using JUnit 4.12, commons-csv 1.2, and Java 8. Please see pom.xml.

Convert String to a Reader object

For simpler tests, you may want to avoid using actual CSV files. Instead, a String containing the CSV data can be converted to a Reader object and passed to the parse(Reader) method.