Top 3 Libraries for Writing and Reading CSV File in Java

Tags: Java CSV Apache Commons CSV Opencsv Super CSV Write CSV Read CSV

Introduction

In this tutorial we’re going to learn how to use open source Java libraries to quickly write and read Comma Separated Values or CSV file format. We will explore 3 useful libraries and implement Java programs to write and read CSV files using each library.

Apache Commons CSV

Home page: commons.apache.org/proper/commons-csv/

Project Dependencies:

Adding below dependencies to build.gradle file if you are using Gradle build tool.

compile group: 'org.apache.commons', name: 'commons-csv', version: '1.8'

Adding below XML to pom.xml file if you are using Maven build tool.

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

Java program to write CSV file with Apache Commons CSV

package dev.simplesolution.commonscsv;

import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

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

public class CommonsCsvWriting {
	
	public static void main(String[] args) throws IOException {
		String outputFileName = "D:\\SimpleSolution\\Contacts.csv";
		String[] headers = new String[] {"First Name", "Last Name" };
		
		try(Writer writer = new FileWriter(outputFileName);
				CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT.withHeader(headers))
						) {
			csvPrinter.printRecord("Dannielle", "Wilks");
			csvPrinter.printRecord("Harvir", "Mathews");
			csvPrinter.printRecord("Sahil", "Rojas");
			csvPrinter.printRecord("Eileen", "Pike");
			csvPrinter.printRecord("Matias", "Moreno");
		}
	}

}

Output file:

Java program to write CSV file with Apache Commons CSV

Java program to read CSV file with Apache Commons CSV

package dev.simplesolution.commonscsv;

import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;

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

public class CommonsCsvReading {
	
	public static void main(String[] args) throws IOException {
		String inputFileName = "D:\\SimpleSolution\\Contacts.csv";
		
		try(Reader reader = new FileReader(inputFileName);
				CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT.withFirstRecordAsHeader().withIgnoreHeaderCase().withTrim())) {
			for(CSVRecord record : csvParser) {
				String firstName = record.get("First Name");
				String lastName = record.get("Last Name");
				
				System.out.println("First Name: " + firstName + ";" + "Last Name: " + lastName);
			}
		}	
	}

}
Program output:

First Name: Dannielle;Last Name: Wilks
First Name: Harvir;Last Name: Mathews
First Name: Sahil;Last Name: Rojas
First Name: Eileen;Last Name: Pike
First Name: Matias;Last Name: Moreno

Opencsv

Home page: opencsv.sourceforge.net/

Project Dependencies:

Adding below dependencies to build.gradle file if you are using Gradle build tool.

compile group: 'com.opencsv', name: 'opencsv', version: '5.1'

Adding below XML to pom.xml file if you are using Maven build tool.

<dependency>
    <groupId>com.opencsv</groupId>
    <artifactId>opencsv</artifactId>
    <version>5.1</version>
</dependency>

Java program to write CSV file with Opencsv

For example we have the POJO Customer class below that needs to write objects of Customer to a CSV file.

package dev.simplesolution.opencsv;

public class Customer {
	private String firstName;
	private String lastName;
	
	public Customer() {
		
	}
	
	public Customer(String firstName, String lastName) {
		super();
		this.firstName = firstName;
		this.lastName = lastName;
	}
	
	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;
	}

	@Override
	public String toString() {
		return "Customer [firstName=" + firstName + ", lastName=" + lastName + "]";
	}
	
}

Java program to write CSV

package dev.simplesolution.opencsv;

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

import com.opencsv.bean.StatefulBeanToCsv;
import com.opencsv.bean.StatefulBeanToCsvBuilder;
import com.opencsv.exceptions.CsvDataTypeMismatchException;
import com.opencsv.exceptions.CsvRequiredFieldEmptyException;

public class OpenCsvWriting {
	
	public static void main(String[] args) throws IOException, CsvDataTypeMismatchException, CsvRequiredFieldEmptyException {
		List<Customer> customers = new ArrayList<Customer>();
		customers.add(new Customer("Sumaiyah", "Armitage"));
		customers.add(new Customer("Zaina", "Howells"));
		customers.add(new Customer("Awais", "Potter"));
		String outputFileName = "D:\\SimpleSolution\\Customers.csv";
		
		try(Writer writer = new FileWriter(outputFileName)) {
			StatefulBeanToCsv<Customer> statefulBeanToCsv = new StatefulBeanToCsvBuilder<Customer>(writer).build();
			statefulBeanToCsv.write(customers);
		}
	}
}

Output CSV file:

Java program to write CSV file with Opencsv

Java program to read CSV file with Opencsv

package dev.simplesolution.opencsv;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.List;

import com.opencsv.bean.CsvToBeanBuilder;

public class OpenCsvReading {
	
	public static void main(String[] args) throws IllegalStateException, FileNotFoundException {
		String inputFileName = "D:\\SimpleSolution\\Customers.csv";
		
		List<Customer> contacts = new CsvToBeanBuilder<Customer>(new FileReader(inputFileName))
				.withType(Customer.class)
				.build()
				.parse();

		for(Customer contact : contacts) {
			System.out.println(contact);
		}

	}

}
Program output:

Customer [firstName=Sumaiyah, lastName=Armitage]
Customer [firstName=Zaina, lastName=Howells]
Customer [firstName=Awais, lastName=Potter]

Super CSV

Home page: super-csv.github.io/super-csv/

Project Dependencies:

Adding below dependencies to build.gradle file if you are using Gradle build tool.

compile group: 'net.sf.supercsv', name: 'super-csv', version: '2.4.0'

Adding below XML to pom.xml file if you are using Maven build tool.

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

Java program to write CSV file with Super CSV

For example we have the POJO Employee class below that needs to write objects of Employee to a CSV file.

package dev.simplesolution.supercsv;

public class Employee {
	
	private String firstName;
	private String lastName;
	
	public Employee() {
		
	}
	
	public Employee(String firstName, String lastName) {
		super();
		this.firstName = firstName;
		this.lastName = lastName;
	}
	
	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;
	}

	@Override
	public String toString() {
		return "Employee [firstName=" + firstName + ", lastName=" + lastName + "]";
	}

}

Java program to write file:

package dev.simplesolution.supercsv;

import java.io.FileWriter;
import java.io.IOException;

import org.supercsv.io.CsvBeanWriter;
import org.supercsv.io.ICsvBeanWriter;
import org.supercsv.prefs.CsvPreference;

public class SuperCsvWriting {
	
	public static void main(String[] args) throws IOException {
		String outputFileName = "D:\\SimpleSolution\\Employees.csv";
		String[] headers = new String[] {"FirstName", "LastName"};
		try(ICsvBeanWriter csvBeanWriter = new CsvBeanWriter(new FileWriter(outputFileName), CsvPreference.STANDARD_PREFERENCE)) {
			csvBeanWriter.writeHeader(headers);
			
			csvBeanWriter.write(new Employee("Ananya", "Cross"), headers);
			csvBeanWriter.write(new Employee("Violet", "Sutherland"), headers);
			csvBeanWriter.write(new Employee("Athena", "Timms"), headers);
			csvBeanWriter.write(new Employee("Anish", "Chapman"), headers);
			csvBeanWriter.write(new Employee("Weronika", "Parkes"), headers);
		}
	}
}

Output CSV file:

Java program to write CSV file with Super CSV

Java program to read CSV file with Super CSV

package dev.simplesolution.supercsv;

import java.io.FileReader;
import java.io.IOException;

import org.supercsv.cellprocessor.constraint.NotNull;
import org.supercsv.cellprocessor.ift.CellProcessor;
import org.supercsv.io.CsvBeanReader;
import org.supercsv.io.ICsvBeanReader;
import org.supercsv.prefs.CsvPreference;

public class SuperCsvReading {
	
	public static void main(String[] args) throws IOException {
		String inputFileName = "D:\\SimpleSolution\\Employees.csv";
		
		try(ICsvBeanReader csvBeanReader = new CsvBeanReader(new FileReader(inputFileName), CsvPreference.STANDARD_PREFERENCE)) {
			final String[] header = csvBeanReader.getHeader(true);
			final CellProcessor[] processors = getProcessors();
			Employee employee = null;
			while( (employee = csvBeanReader.read(Employee.class,  header, processors)) != null) {
				System.out.println(employee);
			}
		}
	}
	
	private static CellProcessor[] getProcessors() {
		final CellProcessor[] processors = new CellProcessor[] {
				new NotNull(),
				new NotNull()
		};
		
		return processors;
	}

}

Program output:

Employee [firstName=Ananya, lastName=Cross]
Employee [firstName=Violet, lastName=Sutherland]
Employee [firstName=Athena, lastName=Timms]
Employee [firstName=Anish, lastName=Chapman]
Employee [firstName=Weronika, lastName=Parkes]

Spring Boot Web Application Download CSV File

Escape or Unescape String for CSV column data in Java using Apache Commons Text

Top 5 Libraries for Serialization and Deserialization JSON in Java

Spring Boot Web Application Download Excel File

Spring Boot Download Excel File Export from MySQL Database