Java – How to read/write CSV file with Apache Commons CSV

In this tutorial, we’re gonna look at examples that read and write CSV file using Apache Commons CSV.

I. Dependency

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

II. Write Data to CSV File

– Simple POJO Customer (id, name, address, age):


package com.javasampleapproach.apachecsv;

public class Customer {
	private String id;
	private String name;
	private String address;
	private int age;

	public Customer() {
	}

	public Customer(String id, String name, String address, int age) {
		this.id = id;
		this.name = name;
		this.address = address;
		this.age = age;
	}

	public String getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public int getAge() {
		return age;
	}

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

	@Override
	public String toString() {
		return "Customer [id=" + id + ", name=" + name + ", address=" + address + ", age=" + age + "]";
	}

}

– Write Customer List to CSV file:


package com.javasampleapproach.apachecsv;

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

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

public class WriteCSV {

	private static final String[] CSV_HEADER = { "id", "name", "address", "age" };

	public static void main(String[] args) {

		List customers = Arrays.asList(
				new Customer("1", "Jack Smith", "Massachusetts", 23),
				new Customer("2", "Adam Johnson", "New York", 27),
				new Customer("3", "Katherin Carter", "Washington DC", 26),
				new Customer("4", "Jack London", "Nevada", 33), 
				new Customer("5", "Jason Bourne", "California", 36));

		FileWriter fileWriter = null;
		CSVPrinter csvPrinter = null;

		try {
			fileWriter = new FileWriter("customer.csv");
			csvPrinter = new CSVPrinter(fileWriter, CSVFormat.DEFAULT.withHeader(CSV_HEADER));

			for (Customer customer : customers) {
				List data = Arrays.asList(
						customer.getId(),
						customer.getName(),
						customer.getAddress(),
						String.valueOf(customer.getAge()));
				
				csvPrinter.printRecord(data);
			}
			
			System.out.println("Write CSV successfully!");
		} catch (Exception e) {
			System.out.println("Writing CSV error!");
			e.printStackTrace();
		} finally {
			try {
				fileWriter.flush();
				fileWriter.close();
				csvPrinter.close();
			} catch (IOException e) {
				System.out.println("Flushing/closing error!");
				e.printStackTrace();
			}
		}
	}
}

– Result in customer.csv file:
read-write-csv-java-result

III. Read Data from CSV File

– Read Customer List from customer.csv file:


package com.javasampleapproach.apachecsv;

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

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

public class ReadCSV {

	public static void main(String[] args) {

		BufferedReader fileReader = null;
		CSVParser csvParser = null;

		try {
			fileReader = new BufferedReader(new FileReader("customer.csv"));
			csvParser = new CSVParser(fileReader,
					CSVFormat.DEFAULT.withFirstRecordAsHeader().withIgnoreHeaderCase().withTrim());

			List customers = new ArrayList();
			
			Iterable csvRecords = csvParser.getRecords();
			
			for (CSVRecord csvRecord : csvRecords) {
				Customer customer = new Customer(
						csvRecord.get("id"),
						csvRecord.get("name"),
						csvRecord.get("address"),
						Integer.parseInt(csvRecord.get("age"))
						);
				
				customers.add(customer);
			}

			for (Customer customer : customers) {
				System.out.println(customer);
			}

		} catch (Exception e) {
			System.out.println("Reading CSV Error!");
			e.printStackTrace();
		} finally {
			try {
				fileReader.close();
				csvParser.close();
			} catch (IOException e) {
				System.out.println("Closing fileReader/csvParser Error!");
				e.printStackTrace();
			}
		}

	}
}

– Result in Console:


Customer [id=1, name=Jack Smith, address=Massachusetts, age=23]
Customer [id=2, name=Adam Johnson, address=New York, age=27]
Customer [id=3, name=Katherin Carter, address=Washington DC, age=26]
Customer [id=4, name=Jack London, address=Nevada, age=33]
Customer [id=5, name=Jason Bourne, address=California, age=36]


By grokonez | February 21, 2018.

Last updated on April 21, 2021.



Related Posts


1 thought on “Java – How to read/write CSV file with Apache Commons CSV”

Got Something To Say:

Your email address will not be published. Required fields are marked *

*