Saturday, November 24, 2012

Parsing a CSV file into JavaBeans using OpenCSV

opencsv is a very useful CSV parsing library for Java.

The following generic utility method shows how you can parse a CSV file into a list of JavaBeans.

/**
 * Parses a csv file into a list of beans.
 *
 * @param <T> the type of the bean
 * @param filename the name of the csv file to parse
 * @param fieldDelimiter the field delimiter
 * @param beanClass the bean class to map csv records to
 * @return the list of beans or an empty list there are none
 * @throws FileNotFoundException if the file does not exist
 */
public static <T> List<T> parseCsvFileToBeans(final String filename,
                          final char fieldDelimiter,
                          final Class<T> beanClass) throws FileNotFoundException {
  CSVReader reader = null;
  try {
    reader = new CSVReader(new BufferedReader(new FileReader(filename)),
                           fieldDelimiter);
    final HeaderColumnNameMappingStrategy<T> strategy =
                                         new HeaderColumnNameMappingStrategy<T>();
    strategy.setType(beanClass);
    final CsvToBean<T> csv = new CsvToBean<T>();
    return csv.parse(strategy, reader);
  } finally {
    if (reader != null) {
      try {
          reader.close();
      } catch (final IOException e) {
          // ignore
      }
    }
  }
}
Example:
Consider the following CSV file containing person information:
FirstName,LastName,Age
Joe,Bloggs,25
John,Doe,30
Create the following Person bean to bind each CSV record to:
public class Person {

  private String firstName;
  private String lastName;
  private int age;

  public Person() {
  }
  public String getFirstName() {
    return firstName;
  }
  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }
  public String getLastName() {
    return lastName;
  }
  public void setLastName(String lastName) {
    this.lastName = lastName;
  }
  public int getAge() {
    return age;
  }
  public void setAge(int age) {
    this.age = age;
  }
}
Now, you can parse the CSV file into a list of Person beans with this one-liner:
List<Person> persons = Utils.parseCsvFileToBeans("/path/to/persons.csv", 
                                                 ',', Person.class);

4 comments:

  1. Why did u use HeaderColumnNameMappingStrategy, why not ColumnPositionMappingStrategy?

    ReplyDelete
  2. The column names map to fields in the Person bean class, that's why you need to use a HeaderColumnNameMappingStrategy.

    ReplyDelete
  3. Could this example be tweaked to handle a list of allowed column names which mean the same thing? Say the csv contains "First Name", "first_name" or "fname" instead of "firstName"?

    ReplyDelete
  4. How can we Parse a CSV file into JavaBeans without using opencsv and/or super CSV ? how can we do that with reflection?

    ReplyDelete