How to Use the Java Library Apache Commons CSV
Apache Commons CSV is a Java library for reading and writing files in CSV, or comma-separated values, format.
Overview
You can read CSV files one line at a time and split them by commas or tabs, but a developer’s real goal should not be parsing CSV itself. The goal should be to read CSV data and then process, transfer, store, or otherwise use it.
Supported CSV formats
- RFC 4180
- MS Excel
- MySQL
- TDF
Custom formats can be created with the fluent style API.
Applying the library
dependencies {
implementation 'org.apache.commons:commons-csv:1.10.0'
}
Reading CSV with the library
The example below reads a CSV file.
package com.devkuma.apache.commons;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
public class ReadCSV {
public static void main(String[] args) {
try {
Reader in = new FileReader("file.csv");
Iterable<CSVRecord> records = CSVFormat.EXCEL.builder().setHeader().build().parse(in);
for (CSVRecord record : records) {
String lastName = record.get("Last Name");
String firstName = record.get("First Name");
System.out.print(lastName + " ");
System.out.println(firstName);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
System.out.println("Done");
}
}
The contents of file.csv are as follows.
"Last Name","First Name"
aaaa,bbbb
cccc,dddd
eeee,ffff
Execution result:
aaaa bbbb
cccc dddd
eeee ffff
Done