Java Write CSV File Example

What is a CSV file? The CSV stands for Comma Separated Value, which means you have a file with rows of columns of data that are separated by a comma. The Apache Commons CSV Library makes writing data in this format pretty easy in your Java program.

In the example below, I am doing development using Eclipse and Maven. The big advantage of a Maven project is that I can quickly add a dependency library to my pom.xml file and I instantly can use the library function that I need.

I added the following dependency to my pom.xml file:


Java Write CSV File Source Code

The Java source code below defines our new csv file called cast.csv. A printer object is created and then we add the column names to the file. Next task is to add some data. If your a Flinstones fan, you will get the humor. I like to then call flush() followed by close() as part of good programming cleanup.


import java.nio.file.Files;
import java.nio.file.Paths;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;

public class JavaWriteCSVFile 

	public static void main(String[] args) 

		//Define CSVPrinter object
		CSVPrinter jcdCSVPrinter;
            //Let's create object 
            Writer jcdWriter = Files.newBufferedWriter(Paths.get("cast.csv"));
            //Let's add column header names
            jcdCSVPrinter = new CSVPrinter(jcdWriter, CSVFormat.DEFAULT.withHeader("First Name", "Last Name", "Age"));
            //Let's add records to our csv file
            jcdCSVPrinter.printRecord("Fred", "Flinstone", 95);
            jcdCSVPrinter.printRecord("Barney", "Rubble" , 90);
            jcdCSVPrinter.printRecord("Wilma", "Flinstone", 85);      
            jcdCSVPrinter.printRecord("Betty", "Rubble", 80);
            //Let's flush or clear the printer object
            //Let's close the printer object
		catch (Exception e) 
			System.out.println("Exception: "+e.toString());


Java Write CSV File Created

You can see the nex cast.csv file created in the base directory. Although it is a CSV text file, you can see that it can be opened using Excel.

Java Write CSV File Contents

Opening the CSV file in Excel shows we successfully created three columns and inputted the data correctly.

Add a Comment

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