Apache Commons CSV

Apache Commons CSV library is used for creating and reading CSV files.

In this post, we are going to see, how we can use this library with an example.

First thing is to include the below dependency in your maven pom file.


 <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-csv</artifactId>
            <version>1.5</version>
  </dependency>

Consider that the employee information is available in a CSV file called (employee.csv). The sample data are given below.

Id First Name Last Name Age
1 John Arthur 25
2 Sam Andrew 26
3 Hary Peter 26

Let’s see how we can read this CSV file in a Java Program with Commons CSV.



import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;

import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;

public class ReadCSVFileMain {

    public static void main(String[] args) throws IOException {

        String filePath = "/tmp/employee.csv";
        List employeeList = new ArrayList();
        Reader reader = null;
        try {
            String[] headers = { "Id", "First Name", "Last Name", "Age" };
            reader = new FileReader(filePath);
            Iterable records = CSVFormat.DEFAULT.withHeader(headers).withFirstRecordAsHeader().parse(reader);
            records.forEach(csvRecord -> {
                Employee employee = new Employee();
                employee.setId(Integer.valueOf(csvRecord.get("Id")));
                employee.setFirstName(csvRecord.get("First Name"));
                employee.setLastName(csvRecord.get("Last Name"));
                employee.setAge(Integer.valueOf(csvRecord.get("Age")));
                employeeList.add(employee);
            });
        }

        finally {
            if (reader != null) {
                reader.close();
            }
        }
        System.out.println("Parsed Content: employeeList::" + employeeList);
    }
}



public class Employee {

    private Integer id;
    private String firstName;
    private String lastName;
    private Integer age;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    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 Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("Employee{");
        sb.append("id=").append(id);
        sb.append(", firstName='").append(firstName).append('\'');
        sb.append(", lastName='").append(lastName).append('\'');
        sb.append(", age=").append(age);
        sb.append('}');
        return sb.toString();
    }

}


The above program is used to parse the employee.CSV file and maps the contents into Employee object. I have created a string array which holds the header names and using that while parsing the file.

The output will be like below,


Parsed Content: employeeList::[Employee{id=1, firstName='John', lastName='Arthur', age=25}, Employee{id=2, firstName='Sam ', lastName='Andrew', age=26}, Employee{id=3, firstName='Hary', lastName=' Peter', age=26}]

Now lets see how we can create a CSV file with an example.



import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;

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

public class CreateCSVFileMain {

    public static void main(String[] args) throws IOException {

        String filePath = "/tmp/employee_new.csv";
        String[] headers = { "Id", "First_Name", "Last_Name", "Age" };
        List employeeList = new ArrayList();
        Employee employee1 = new Employee();
        employee1.setId(1234);
        employee1.setFirstName("fname1");
        employee1.setLastName("lname1");
        employee1.setAge(45);
        Employee employee2 = new Employee();
        employee2.setId(1234);
        employee2.setFirstName("fname1");
        employee2.setLastName("lname1");
        employee2.setAge(45);
        employeeList.add(employee1);
        employeeList.add(employee2);

        FileWriter writer = null;
        try {
            writer = new FileWriter(filePath);
            try (CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT.withHeader(headers))) {
                employeeList.forEach(employee -> {
                    try {
                        csvPrinter.printRecord(employee.getId(), employee.getFirstName(), employee.getLastName(),
                                               employee.getAge());
                    }
                    catch (IOException io) {
                        io.printStackTrace();
                    }
                });
            }
        }
        finally {
            if (writer != null) {
                writer.close();
            }
        }
    }
}


If we don’t want the header then, don’t specify with header.
The content of the created employee_new.csv file is given below,


Id,First_Name,Last_Name,Age
1234,fname1,lname1,45
1234,fname1,lname1,45

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s