In this tutorial, I will guide you how to write Java code to read data from a CSV file.

Super CSV is the most powerful open-source library for reading, writing and processing CSV files written in Java programming language. It is fast and easy to use with POJO (Plain Old Java Object) support. In this tutorial, we show you how to use Super CSV to read CSV files using CsvBeanReader class which reads each line into a JavaBean class (POJO).

To use Super CSV, add super-csv-VERSION.jar file to the classpath or use the following Maven dependency:

<dependency>
    <groupId>net.sf.supercsv</groupId>
    <artifactId>super-csv</artifactId>
    <version>VERSION</version>
</dependency>
Replace VERSION by the actual version number, i.e. 2.1.0 is the current version of Super CSV.

 

1. Sample CSV File

We use a sample CSV file (Books.csv) with the following content:

isbn,title,author,publisher,published,price
0321356683,Effective Java,Joshua Bloch,Addision-Wesley,05/08/2008,38
0321356683,Head First Java,Kathy Sierra & Bert Bates,O'Reilly Media,02/09/2005,30
0131872486,Thinking in Java,Bruce Eckel,Prentice Hall,02/26/2006,45
0596527756,Java Generics and Collections,Naftalin & Philip Wadler,O'Reilly Media,10/24/2006,27
Note that the first line contains the header columns, and the subsequent lines are actual data. The column delimiter here is comma.


2. Creating POJO class

Write a POJO - JavaBean class (Book.java) with the following code:

package net.codejava.supercsv;

import java.util.Date;

public class Book {
	private String isbn;
	private String title;
	private String author;
	private String publisher;
	private Date published;
	private double price;

	public Book() {
		// this empty constructor is required
	}

	public Book(String isbn, String title, String author, String publisher,
			Date published, double price) {
		this.isbn = isbn;
		this.title = title;
		this.author = author;
		this.publisher = publisher;
		this.published = published;
		this.price = price;
	}

	// getters and setters
}
This POJO class defines fields that match the column headers in the CSV file. Remember to supply complete code for the getters and setters.


3. Creating cell processors



Super CSV provides some classes called cell processors that automate data type conversions and enforce constraints when mapping values in the CSV file with JavaBean’s properties. For example: the NotNull processor ensures that the column is not null; the ParseDate processor converts a String to a Date object using a specified date format; the ParseDouble processor converts a String to a Double.

For the above CSV file and JavaBean class, we create the following array of processors:

CellProcessor[] processors = new CellProcessor[] {
		new NotNull(), // ISBN
		new NotNull(), // title
		new NotNull(), // author
		new NotNull(), // publisher
		new ParseDate("MM/dd/yyyy"), // published date
		new ParseDouble() // price
};
Note that the order of processors must match the order of columns in the CSV file.


4. Reading CSV file with CsvBeanReader

The following code snippet gives you an idea of how to read the sample CSV file using the CsvBeanReader class with the above cell processors:

ICsvBeanReader beanReader = new CsvBeanReader(new FileReader(csvFileName),
					CsvPreference.STANDARD_PREFERENCE);

String[] header = beanReader.getHeader(true);
Book bookBean = null;

while ((bookBean = beanReader.read(Book.class, header, processors)) != null) {
	// deals with each bean read
	String ISBN = bookBean.getIsbn();
	//...
}
Here, the while loop reads each line (after the first line of column headers) into a Book object until reaching the end of the CSV file. Which column is mapped to which Book’s field is specified by the header array:

String[] header = beanReader.getHeader(true);
In this case, the header is read from the first line in the CSV file, and the column names must match the field names in the JavaBean class:

isbn,title,author,publisher,published,price
The following code is a complete method:

static void readCSVFile(String csvFileName) {
	ICsvBeanReader beanReader = null;
	CellProcessor[] processors = new CellProcessor[] {
			new NotNull(), // ISBN
			new NotNull(), // title
			new NotNull(), // author
			new NotNull(), // publisher
			new ParseDate("MM/dd/yyyy"), // published date
			new ParseDouble() // price
	};

	try {
		beanReader = new CsvBeanReader(new FileReader(csvFileName),
				CsvPreference.STANDARD_PREFERENCE);
		String[] header = beanReader.getHeader(true);
		Book bookBean = null;
		while ((bookBean = beanReader.read(Book.class, header, processors)) != null) {
			System.out.printf("%s %-30s %-30s %-20s %tD $%.2f",
					bookBean.getIsbn(), bookBean.getTitle(),
					bookBean.getAuthor(), bookBean.getPublisher(),
					bookBean.getPublished(), bookBean.getPrice());
			System.out.println();
		}
	} catch (FileNotFoundException ex) {
		System.err.println("Could not find the CSV file: " + ex);
	} catch (IOException ex) {
		System.err.println("Error reading the CSV file: " + ex);
	} finally {
		if (beanReader != null) {
			try {
				beanReader.close();
			} catch (IOException ex) {
				System.err.println("Error closing the reader: " + ex);
			}
		}
	}
}
This method reads data out from the specified CSV file, with each line is read into a Book object, and then prints the book details to the standard output.


5. Java Read CSv File Example program

Write a simple test program like this:

package net.codejava.supercsv;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import org.supercsv.cellprocessor.ParseDate;
import org.supercsv.cellprocessor.ParseDouble;
import org.supercsv.cellprocessor.constraint.NotNull;
import org.supercsv.cellprocessor.ift.CellProcessor;
import org.supercsv.io.CsvBeanReader;
import org.supercsv.io.ICsvBeanReader;
import org.supercsv.prefs.CsvPreference;

/**
 * This program demonstrates how to read CSV file using SuperCSV library.
 * Each line is read into a JavaBean class (POJO).
 * @author www.codejava.net
 *
 */
public class CsvBeanReaderExample {

	static void readCSVFile(String csvFileName) {
		// same code as the method above
	}

	public static void main(String[] args) {
		String csvFileName = "Books.csv";
		readCSVFile(csvFileName);
	}
}
Output:

0321356683 Effective Java                 Joshua Bloch                   Addision-Wesley      05/08/08 $38.00
0321356683 Head First Java                Kathy Sierra & Bert Bates      O'Reilly Media       02/09/05 $30.00
0131872486 Thinking in Java               Bruce Eckel                    Prentice Hall        02/26/06 $45.00
0596527756 Java Generics and Collections  Naftalin & Philip Wadler       O'Reilly Media       10/24/06 $27.00

You can get the code example on GitHub or download the sample code below.

To write data to a CSV file, refer to this tutorial: Java Write CSV File Example

 

References:

 

Other Java Coding Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.



Attachments:
Download this file (CsvBeanReaderExample.zip)CsvBeanReaderExample.zip[Java source files]3 kB

Add comment

   


Comments 

#3Thyag Sundaramoorthy2020-07-29 08:28
How to collect exceptions to a list if cell processor validation exception occurs? If my csv has 1000 records, and if line 5 has wrong data, continue to process until end of file.
Quote
#2Kathiravan2016-02-03 12:33
Hi I have a pojo with many properties, one of the properties is List, how do i define in the cell processor.
Am getting error org.supercsv.exception.SuperCsvReflectionException: unable to find method setParentCategory(java.lang.String) in class
Quote
#1Jerry Sivan2015-05-17 09:17
Thanks for the article, and I’m sharing one more open-source library for reading/writing/mapping CSV data. Since I used this library in my project, I found out it powerful and flexiable especially parsing big CSV data (such as 1GB+ file or complex processing logic).

Here are the code snippts programming the functionalities included in this article:

// 1st, config the CSV reader with line separator
CsvParserSettings settings = new CsvParserSettings();
settings.getFormat().setLineSeparator("\n");

// 2nd, config the CSV reader with row processor attaching the bean definition
BeanListProcessor rowProcessor = new BeanListProcessor(Employee.class);
settings.setRowProcessor(rowProcessor);

// 3rd, parse all rows from the CSF file into the list of beans you defined
CsvParser parser = new CsvParser(settings);
parser.parse(new FileReader("/examples/employees.csv"));
List resolvedBeans = rowProcessor.getBeans();
Quote