How to read CSV File using Super Csv with CsvBeanReader
A CSV (Comma Sepearted Value) file is a text file that has a header with matching values. CSV Files can have different delimiters. With SuperCsv Reading CSV files is straightforward. This open source library allows you to easily customize the type of CSV you want to parse. In the following example we show you how you can read a CSV File.
Maven Dependency
As we are working with an open source library you need to add the following snippit to your pom.xml.
<dependency>
<groupId>net.sf.supercsv</groupId>
<artifactId>super-csv</artifactId>
<version>2.3.0</version>
</dependency>
CSV File
id,name,description,price,date
1,"SuperCsv",,1200.5,30/01/2015
2,"Java","Java Course",987.5,30/01/2015
Bean Definition
As we are using a CsvBeanReader
we need to map all the csv columns to our bean to allow the reader to parse the CSV correctly.
package com.memorynotfound.csv;
import java.util.Date;
public class Course {
private Integer id;
private String name;
private String description;
private Double price;
private Date date;
/**
* Default no-args constructor
*/
public Course() {
}
public Course(Integer id, String name, String description, Double price, Date date) {
this.id = id;
this.name = name;
this.description = description;
this.price = price;
this.date = date;
}
// getters and setters
@Override
public String toString() {
return "Course{" +
"id=" + id +
", name='" + name + '\'' +
", description='" + description + '\'' +
", price=" + price +
", date=" + date +
'}';
}
}
Csv File Reader
Here we are creating a new CsvBeanReader
which we’ll use to parse/read the CSV File. Note that the reader takes a CsvPreference
as the second argument, here we could configure what type of delimiter to use for reading the CSV File. With the CellProcessor
you can map the corresponding fields with their type and validate if one of the expected fields are invalid.
package com.memorynotfound.csv;
import org.supercsv.cellprocessor.*;
import org.supercsv.cellprocessor.constraint.NotNull;
import org.supercsv.cellprocessor.ift.CellProcessor;
import org.supercsv.io.CsvBeanReader;
import org.supercsv.io.CsvBeanWriter;
import org.supercsv.io.ICsvBeanReader;
import org.supercsv.io.ICsvBeanWriter;
import org.supercsv.prefs.CsvPreference;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class CsvFileReader {
public static void readCsv(String csvFileName) throws IOException {
ICsvBeanReader beanReader = null;
try {
beanReader = new CsvBeanReader(new FileReader(csvFileName), CsvPreference.STANDARD_PREFERENCE);
// the header elements are used to map the values to the bean (names must match)
final String[] header = beanReader.getHeader(true);
final CellProcessor[] processors = getProcessors();
Course course;
while ((course = beanReader.read(Course.class, header, processors)) != null) {
// process course
System.out.println(course);
}
} finally {
if (beanReader != null) {
beanReader.close();
}
}
}
private static CellProcessor[] getProcessors(){
return new CellProcessor[] {
new ParseInt(),
new NotNull(),
new Optional(),
new ParseDouble(),
new ParseDate("dd/MM/yyyy")};
}
}
Reading a CSV File
package com.memorynotfound.csv;
import java.io.IOException;
public class ReadCourseCsv {
public static void main(String... args) throws IOException {
// get file from resources folder
String fileName = ReadCourseCsv.class.getResource("/courses.csv").getFile();
// read csv
CsvFileReader.readCsv(fileName);
}
}
Output
Course{id=1, name='SuperCsv', description='null', price=1200.5, date=Fri Jan 30 00:00:00 CET 2015}
Course{id=2, name='Java', description='Java Course', price=987.5, date=Fri Jan 30 00:00:00 CET 2015}
Thanks for the article, and I’m sharing one more open-source library uniVocity-parsers (http://www.univocity.com/pages/parsers-tutorial) for parsing CSV data. In my project, I found it powerful and flexiable, especially when parsing big CSV data (such as 1GB+). The library provides simplified API, and full capabilities in parsing CSV file, such as quote espacing, headers extraction, column selection, mapping to Java Beans and so on. Here is a code snippt for using this library: public static void main(String[] args) throws FileNotFoundException { /** * ————————————— * Read CSV rows into 2-dimensional array * ————————————— */ // 1st, config the CSV reader, such as… Read more »