CSV to Bean
Super CSV is a free library for reading and writing
CSV files in Java. We need to have SuperCSV-1.52.jar, spiffy-0.05.jar or
later versions in classpath.
The following example shows populating java beans from CSV using Super CSV.
User can provide a CellProcessor or
Chain of CellProcessors for CSV data conversion.
package com.bethecoder.tutorials.super_csv.tests;
import java.io.IOException;
import java.io.StringReader;
import org.supercsv.cellprocessor.ParseInt;
import org.supercsv.cellprocessor.ift.CellProcessor;
import org.supercsv.io.CsvBeanReader;
import org.supercsv.prefs.CsvPreference;
import com.bethecoder.tutorials.super_csv.common.Student;
public class CSV2Bean {
/**
* @param args
* @throws IOException
*/
public static void main ( String [] args ) throws IOException {
//CSV header names matching with bean properties
String CSV =
"name,age,hobby\n" +
"Sriram,2,Chess\n" +
"Sudhakar,29,Painting" ;
CsvBeanReader reader = new CsvBeanReader ( new StringReader ( CSV ) ,
CsvPreference.STANDARD_PREFERENCE ) ;
//Read headers
String [] headers = reader.getCSVHeader ( true ) ;
/**
* Name and hobby doesn't require any processing
* But age has to be converted to int before
* setting the bean property.
*/
CellProcessor [] processors = {
//name, age, hobby
null, new ParseInt () , null
} ;
Student student = null ;
while (( student = reader.read ( Student.class, headers, processors )) != null ) {
System.out.println ( student ) ;
}
}
}
package com.bethecoder.tutorials.open_csv.common;
public class Student {
private String name;
private int age;
private String hobby;
public Student () {
}
public Student ( String name, int age, String hobby ) {
super () ;
this .name = name;
this .age = age;
this .hobby = hobby;
}
public String getName () {
return name;
}
public void setName ( String name ) {
this .name = name;
}
public int getAge () {
return age;
}
public void setAge ( int age ) {
this .age = age;
}
public String getHobby () {
return hobby;
}
public void setHobby ( String hobby ) {
this .hobby = hobby;
}
public String toString () {
return "Student[name = " + name + ", age = " + age + ", hobby = " + hobby + "]" ;
}
}
It gives the following output,
Student[name = Sriram, age = 2, hobby = Chess]
Student[name = Sudhakar, age = 29, hobby = Painting]