How to Write CSV File with Super CSV and CsvBeanWriter

Writing Java Objects to a CSV File using Super CSV Library is straightforward. It has a Clear and flexible API to read and write every type of object you want to and from a CSV File. In the following example we will write CSV File using plaint java objects. You can specify which headers, delimiters, quotes and end of line characters to use.

Maven Dependency

Add the super csv to your maven dependencies.

<dependency>
    <groupId>net.sf.supercsv</groupId>
    <artifactId>super-csv</artifactId>
    <version>2.3.0</version>
</dependency>

Bean Definition

Here is a representation of the Java Object we are going to write to the CSV file.

package com.memorynotfound.csv;

import java.util.Date;

public class Course {

    private Integer id;
    private String name;
    private String description;
    private Double price;
    private Date date;

    /**
     * Default no-args constructor
     */
    public Course() {
    }

    public Course(Integer id, String name, String description, Double price, Date date) {
        this.id = id;
        this.name = name;
        this.description = description;
        this.price = price;
        this.date = date;
    }

    // getters and setters

    @Override
    public String toString() {
        return "Course{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", description='" + description + '\'' +
                ", price=" + price +
                ", date=" + date +
                '}';
    }
}

Csv File Writer

First we create a CsvBeanWriter which takes a CsvPreference as the second parameter which represents the CSV Configuration which Super CSV uses to write/read a CSV File.

Note: Here is an example how to customise delimiter for CSV File:
public CsvPreference customCsvPreference(){
    return new CsvPreference.Builder('|', ',', "\n").build();
}

Super CSV has CellProcessors that convert Java data types to Strings and vice-versa. They automate the data type conversions, and enforce constraints. Some examples are Unique which makes sure all the values are unique. Another one is FmtDate which formats the date in the particular string representation.

package com.memorynotfound.csv;

import org.supercsv.cellprocessor.*;
import org.supercsv.cellprocessor.constraint.*;
import org.supercsv.cellprocessor.ift.CellProcessor;
import org.supercsv.io.*;
import org.supercsv.prefs.CsvPreference;

import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

public class CsvFileWriter {

    public CsvPreference customCsvPreference(){
        return new CsvPreference.Builder('|', ',', "\n").build();
    }

    public static void writeCsv(String csvFileName, List<Course> courses) throws IOException {
        ICsvBeanWriter beanWriter = null;
        try {
            beanWriter = new CsvBeanWriter(new FileWriter(csvFileName), CsvPreference.STANDARD_PREFERENCE);

            // the header elements are used to map the bean values to each column (names must match)
            final String[] header = new String[] { "id", "name", "description", "price", "date"};
            final CellProcessor[] processors = getProcessors();

            // write the header
            beanWriter.writeHeader(header);

            // write the beans
            for(final Course course : courses ) {
                beanWriter.write(course, header, processors);
            }
        } finally {
            if( beanWriter != null ) {
                beanWriter.close();
            }
        }
    }

    private static CellProcessor[] getProcessors(){
        return new CellProcessor[] {
                new Unique(new ParseInt()),
                new NotNull(),
                new Optional(),
                new ParseDouble(),
                new FmtDate("dd/MM/yyyy")};
    }
}

Writing our CSV File

package com.memorynotfound.csv;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class WriteCourseCsv {

    public static void main(String... args) throws IOException {

        // get file from resources folder
        String fileName = "/tmp/courses.csv";

        List<Course> courses = new ArrayList<>();
        courses.add(new Course(1, "SuperCsv", "Write csv file", 1234.56, new Date()));
        courses.add(new Course(2, "SuperCsv", "Read csv file", 1234.56, new Date()));

        // write csv
        CsvFileWriter.writeCsv(fileName, courses);
    }
}

Output

id,name,description,price,date
1,SuperCsv,Write csv file,1234.56,04/03/2015
2,SuperCsv,Read csv file,1234.56,04/03/2015

References

Download

You may also like...