Read and Write a CSV File in Java using OpenCSV Library

This tutorial shows you how to read and write a CSV file in Java using OpenCSV library.

OpenCSV is a simple Java library for reading and writing CSV files.

A CSV (comma-separated-values) file is a standard text file in which values are separated by commas. Following is an example of a CSV file:

example-file.csv
Name,Email,Year,Programming
"Danny","[email protected]",2021,"Java" "Lenny","[email protected]",2020,"Python" "John","[email protected]",2017,"Go" "Sam","[email protected]",2019,"Node JS"

Follow the steps below to read and write a CSV file in Java:

Add OpenCSV Library

Add OpenCSV library to your project. Find the lastest version of the OpenCSV in the OpenCSV Maven Repository.

For Maven

pom.xml


For Gradle

build.gradle

    implementation group: 'com.opencsv', name: 'opencsv', version: '5.5.2'

Read CSV File

The following code reads a CSV file line by line:


CSVReader reader;
try {
	reader = new CSVReader(new FileReader("C:\\Documents\\example-file.csv"));
	String[] row;
	int count = 0;
	while ((row = reader.readNext()) != null) {
		count++;
		System.out.println("Column 1 = " + row[0]);
		System.out.println("Column 2 = " + row[1]);
	    }
	System.out.println("Total number of rows = " + count);
	} catch (CsvValidationException | IOException e) {
		e.printStackTrace();
	}

Here is a complete example of reading a CSV file in Java:


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

import com.opencsv.CSVReader;
import com.opencsv.exceptions.CsvValidationException;

public class ReadCsvFileExample {

	public static void main(String[] args) {

		CSVReader reader;
		try {
			reader = new CSVReader(new FileReader("C:\\Documents\\example-file.csv"));
			String[] row;
			int count = 0;
			while ((row = reader.readNext()) != null) {
				count++;
				System.out.println("Column 1 = " + row[0]);
				System.out.println("Column 2 = " + row[1]);
			}
			System.out.println("Total number of rows = " + count);
		} catch (CsvValidationException | IOException e) {
			e.printStackTrace();
		}

	}
}

Write CSV File

The following code creates a CSV file data in it:


CSVWriter writer = null;
try {
    //location to write the CSV file
    String path = "C:\\Documents\\example-file2.csv";
    FileWriter outputfile = new FileWriter(new File(path));

    writer = new CSVWriter(outputfile);

    // create a List of String array
    List<String[]> dataToWrite = new ArrayList<String[]>();
    dataToWrite.add(new String[] { "Name", "Email", "Year", "Programming" });
    dataToWrite.add(new String[] { "John", "[email protected]","2021","Java" });
    dataToWrite.add(new String[] { "Danny", "[email protected]", "2020", "Python" });
    dataToWrite.add(new String[] { "Lenny", "[email protected]", "2021", "Go" });
    dataToWrite.add(new String[] { "Sam", "[email protected]", "2019", "Node JS" });
                
    writer.writeAll(dataToWrite);
    System.out.println("Complete");
} catch (IOException e) {
	e.printStackTrace();
} finally {
	try {
	    if (writer != null)
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
}

Here is a complete example of writing data to a CSV file in Java:


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

import com.opencsv.CSVWriter;

public class ReadCsvFileExample {

	public static void main(String[] args) {
		CSVWriter writer = null;
		try {
            //location to write the CSV file
			String path = "C:\\Documents\\example-file2.csv";
			FileWriter outputfile = new FileWriter(new File(path));

			writer = new CSVWriter(outputfile);

			// create a List of String array
			List<String[]> dataToWrite = new ArrayList<String[]>();
			dataToWrite.add(new String[] { "Name", "Email", "Year", "Programming" });
			dataToWrite.add(new String[] { "John", "[email protected]","2021","Java" });
			dataToWrite.add(new String[] { "Danny", "[email protected]", "2020", "Python" });
			dataToWrite.add(new String[] { "Lenny", "[email protected]", "2021", "Go" });
			dataToWrite.add(new String[] { "Sam", "[email protected]", "2019", "Node JS" });
			
			writer.writeAll(dataToWrite);
            System.out.println("Complete");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (writer != null)
					writer.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}
}