CSV > OPEN CSV > CSV to Bean using Header to Column Name Mapping Strategy
CSV to Bean using Header to Column Name Mapping Strategy
opencsv is a free and open source library for reading and writing
CSV files in Java. We need to have opencsv-2.3.jar or
later versions in classpath.
The following example shows populating a java bean from CSV using opencsv.
The CSV header (the first row in CSV which describes all other rows) names
should match with bean property names when using this strategy.
package com.bethecoder.tutorials.open_csv.tests;
import java.io.StringReader;
import java.util.List;
import au.com.bytecode.opencsv.bean.CsvToBean;
import au.com.bytecode.opencsv.bean.HeaderColumnNameMappingStrategy;
import com.bethecoder.tutorials.open_csv.common.Student;
public class CSV2BeanColumnName {
/**
* @param args
*/
public static void main ( String [] args ) {
//CSV header names matching with bean properties
String CSV =
"name,age,hobby\n" +
"Sriram,2,Chess\n" +
"Sudhakar,29,Painting" ;
CsvToBean<Student> bean = new CsvToBean<Student> () ;
//Define strategy
HeaderColumnNameMappingStrategy<Student> strategy =
new HeaderColumnNameMappingStrategy<Student> () ;
strategy.setType ( Student. class ) ;
//Parse the CSV
List<Student> students = bean.parse ( strategy, new StringReader ( CSV )) ;
System.out.println ( students ) ;
}
}
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]]