tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 CSV > OPEN CSV > CSV to Bean using Column Position Mapping Strategy

CSV to Bean using Column Position 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. This strategy is useful when parsing CSVs without any header. We need to specify an explicit mapping between CSV column position/index and property name of bean using setColumnMapping method. The order of properties specified should match with CSV column data.

File Name  :  
com/bethecoder/tutorials/open_csv/tests/CSV2BeanColumnPosition.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.open_csv.tests;

import java.io.StringReader;
import java.util.List;

import au.com.bytecode.opencsv.bean.ColumnPositionMappingStrategy;
import au.com.bytecode.opencsv.bean.CsvToBean;

import com.bethecoder.tutorials.open_csv.common.Student;

public class CSV2BeanColumnPosition {

  /**
   @param args
   */
  public static void main(String[] args) {

    //CSV with no headers
    String CSV = 
      "Sriram, 2, Chess\n" +
      "Sudhakar, 29, Painting";
    
    CsvToBean<Student> bean = new CsvToBean<Student>();
    
    //Define strategy
    ColumnPositionMappingStrategy<Student> strategy = 
        new ColumnPositionMappingStrategy<Student>();
    strategy.setType(Student.class);
    strategy.setColumnMapping(new String [] { "name""age""hobby" });
    
    //Parse the CSV
    List<Student> students = bean.parse(strategy, new StringReader(CSV));
        System.out.println(students);
  }
}
   

File Name  :  
com/bethecoder/tutorials/open_csv/common/Student.java 
   
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]]



 
  


  
bl  br