How to read CSV file in java using jackson
This article demonstrates how to read a CSV file in java using Jackson library.
| UPDATED
Jackson dataformat csv
Jackson is the most popular library parse JSON in java. In this article I will should you that using Jackson API you can parse CSV file too.
Suppose we have a below CSV content
firstName,lastName,age
Chintan,Radia,29
and let say we want to read the CSV content into below Java class.
public class User {
private String firstName;
private String lastName;
private String age;
// getters and setters
@Override
public String toString() {
return "User{" +
"firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", age='" + age + '\'' +
'}';
}
}
The first thing we need to do is to get jackson-dataformat-csv
in our project, here I am working with maven project so we will add its dependency in our pom.xml
file as below.
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-csv</artifactId>
<version>2.12.0</version>
</dependency>
</dependencies>
and now to use it’s api to read CSV file we can write Java code as below
public class Main {
public static void main(String[] args) throws IOException {
File csvFile = new File("/data/users.csv");
// Create CSVSchema, here we are having csv with headers in it, so we can
// use .withHeader option this will instruct Jackson that you need to read first line
// of CSV file to get the column names, and those column names will be used to map its value
// with User object's property.
CsvSchema schema = CsvSchema.emptySchema().withHeader();
ObjectReader objectReader = new CsvMapper().readerFor(User.class).with(schema);
MappingIterator<User> userMappingIterator = objectReader.readValues(csvFile);
System.out.println(userMappingIterator.readAll());
}
}
On executing above code, it will print below text in console.
[User{firstName='Chintan', lastName='Radia', age='29'}]
Jackson DataFormat API comes with many feature, you can read about more about it here jackson-dataformats-text