csv

Write/Read CSV Files with Apache Commons CSV Example

In this example we will continue to demonstrate how to Write/Read CSV (Comma Separated Values) files in java. In our previous example, we already show how to do that using a native Java code. However, this example will illustrate how to write and read CSV files with an open source 3rd Party tool “Apache Commons CSV”, Apache Commons CSV library provides a simple interface for reading and writing CSV files of various types.

So, Let’s see how we can write and read a simple CSV file using the Apache Commons CSV.

The latest stable release of Commons CSV is 1.0, we can download it from here or we can pull it from the central Maven repositories using the following dependency in your project POM:

1. Dependencies:

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

2. POJO to map the CSV File:

We create this simple POJO to contain the student data like id, firstName, lastName, gender and age.

Student.java:

package com.jcg;

/**
 * @author ashraf
 *
 */
public class Student {
	
	private long id;
	private String firstName;
	private String lastName;
	private String gender;
	private int age;
	/**
	 * @param id
	 * @param firstName
	 * @param lastName
	 * @param gender
	 * @param age
	 */
	public Student(long id, String firstName, String lastName, String gender,
			int age) {
		super();
		this.id = id;
		this.firstName = firstName;
		this.lastName = lastName;
		this.gender = gender;
		this.age = age;
	}
	/**
	 * @return the id
	 */
	public long getId() {
		return id;
	}
	/**
	 * @param id the id to set
	 */
	public void setId(long id) {
		this.id = id;
	}
	/**
	 * @return the firstName
	 */
	public String getFirstName() {
		return firstName;
	}
	/**
	 * @param firstName the firstName to set
	 */
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	/**
	 * @return the lastName
	 */
	public String getLastName() {
		return lastName;
	}
	/**
	 * @param lastName the lastName to set
	 */
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	/**
	 * @return the gender
	 */
	public String getGender() {
		return gender;
	}
	/**
	 * @param gender the gender to set
	 */
	public void setGender(String gender) {
		this.gender = gender;
	}
	/**
	 * @return the age
	 */
	public int getAge() {
		return age;
	}
	/**
	 * @param age the age to set
	 */
	public void setAge(int age) {
		this.age = age;
	}
	
	@Override
	public String toString() {
		return "Student [id=" + id + ", firstName=" + firstName
				+ ", lastName=" + lastName + ", gender=" + gender + ", age="
				+ age + "]";
	}
}

3. Write to CSV File:

CsvFileWriter creates a comma separated value format “CSV” file from a set of students data and save it in your home directory. Firstly, it writes the CSV file header, and then it writes the students data using CSVPrinter class.

CsvFileWriter.java:

package com.jcg;

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

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

/**
 * @author ashraf
 * 
 */
public class CsvFileWriter {
	
	//Delimiter used in CSV file
	private static final String NEW_LINE_SEPARATOR = "\n";
	
	//CSV file header
	private static final Object [] FILE_HEADER = {"id","firstName","lastName","gender","age"};

	public static void writeCsvFile(String fileName) {
		
		//Create new students objects
		Student student1 = new Student(1, "Ahmed", "Mohamed", "M", 25);
		Student student2 = new Student(2, "Sara", "Said", "F", 23);
		Student student3 = new Student(3, "Ali", "Hassan", "M", 24);
		Student student4 = new Student(4, "Sama", "Karim", "F", 20);
		Student student5 = new Student(5, "Khaled", "Mohamed", "M", 22);
		Student student6 = new Student(6, "Ghada", "Sarhan", "F", 21);
		
		//Create a new list of student objects
		List students = new ArrayList();
		students.add(student1);
		students.add(student2);
		students.add(student3);
		students.add(student4);
		students.add(student5);
		students.add(student6);
		
		FileWriter fileWriter = null;
		
		CSVPrinter csvFilePrinter = null;
		
		//Create the CSVFormat object with "\n" as a record delimiter
        CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator(NEW_LINE_SEPARATOR);
				
		try {
			
			//initialize FileWriter object
			fileWriter = new FileWriter(fileName);
			
			//initialize CSVPrinter object 
	        csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);
	        
	        //Create CSV file header
	        csvFilePrinter.printRecord(FILE_HEADER);
			
			//Write a new student object list to the CSV file
			for (Student student : students) {
				List studentDataRecord = new ArrayList();
	            studentDataRecord.add(String.valueOf(student.getId()));
	            studentDataRecord.add(student.getFirstName());
	            studentDataRecord.add(student.getLastName());
	            studentDataRecord.add(student.getGender());
	            studentDataRecord.add(String.valueOf(student.getAge()));
	            csvFilePrinter.printRecord(studentDataRecord);
			}

			System.out.println("CSV file was created successfully !!!");
			
		} catch (Exception e) {
			System.out.println("Error in CsvFileWriter !!!");
			e.printStackTrace();
		} finally {
			try {
				fileWriter.flush();
				fileWriter.close();
				csvFilePrinter.close();
			} catch (IOException e) {
				System.out.println("Error while flushing/closing fileWriter/csvPrinter !!!");
                e.printStackTrace();
			}
		}
	}
}

Let’s see how the generated student.csv file is organized, it contains the header and the students data below.

student.csv:

id,firstName,lastName,gender,age
1,Ahmed,Mohamed,M,25
2,Sara,Said,F,23
3,Ali,Hassan,M,24
4,Sama,Karim,F,20
5,Khaled,Mohamed,M,22
6,Ghada,Sarhan,F,21

4. Read from CSV File:

CsvFileReader reads the CSV file in java using CSVParser class then skipping the header and starting from the second line, we read each line using CSVRecord class. Finally, we create a new list of student and print it.

CsvFileReader.java:

package com.jcg;

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;

/**
 * @author ashraf_sarhan
 *
 */
public class CsvFileReader {
	
	//CSV file header
    private static final String [] FILE_HEADER_MAPPING = {"id","firstName","lastName","gender","age"};
	
	//Student attributes
	private static final String STUDENT_ID = "id";
	private static final String STUDENT_FNAME = "firstName";
	private static final String STUDENT_LNAME = "lastName";
	private static final String STUDENT_GENDER = "gender"; 
	private static final String STUDENT_AGE = "age";
	
	public static void readCsvFile(String fileName) {

		FileReader fileReader = null;
		
		CSVParser csvFileParser = null;
		
		//Create the CSVFormat object with the header mapping
        CSVFormat csvFileFormat = CSVFormat.DEFAULT.withHeader(FILE_HEADER_MAPPING);
     
        try {
        	
        	//Create a new list of student to be filled by CSV file data 
        	List students = new ArrayList();
            
            //initialize FileReader object
            fileReader = new FileReader(fileName);
            
            //initialize CSVParser object
            csvFileParser = new CSVParser(fileReader, csvFileFormat);
            
            //Get a list of CSV file records
            List csvRecords = csvFileParser.getRecords(); 
            
            //Read the CSV file records starting from the second record to skip the header
            for (int i = 1; i < csvRecords.size(); i++) {
            	CSVRecord record = csvRecords.get(i);
            	//Create a new student object and fill his data
            	Student student = new Student(Long.parseLong(record.get(STUDENT_ID)), record.get(STUDENT_FNAME), record.get(STUDENT_LNAME), record.get(STUDENT_GENDER), Integer.parseInt(record.get(STUDENT_AGE)));
                students.add(student);	
			}
            
            //Print the new student list
            for (Student student : students) {
				System.out.println(student.toString());
			}
        } 
        catch (Exception e) {
        	System.out.println("Error in CsvFileReader !!!");
            e.printStackTrace();
        } finally {
            try {
                fileReader.close();
                csvFileParser.close();
            } catch (IOException e) {
            	System.out.println("Error while closing fileReader/csvFileParser !!!");
                e.printStackTrace();
            }
        }

	}

}

5. Run the Example:

CsvWriteReadTest is the main class to run CsvFileWriter and CsvFileReader for the given CSV file.

CsvWriteReadTest.java:

package com.jcg;

/**
 * @author ashraf
 *
 */
public class CsvWriteReadTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		String fileName = System.getProperty("user.home")+"/student.csv";
		
		System.out.println("Write CSV file:");
		CsvFileWriter.writeCsvFile(fileName);
		
		System.out.println("\nRead CSV file:");
		CsvFileReader.readCsvFile(fileName);

	}

}

Output:

Write CSV file:
CSV file was created successfully !!!

Read CSV file:
Student [id=1, firstName=Ahmed, lastName=Mohamed, gender=M, age=25]
Student [id=2, firstName=Sara, lastName=Said, gender=F, age=23]
Student [id=3, firstName=Ali, lastName=Hassan, gender=M, age=24]
Student [id=4, firstName=Sama, lastName=Karim, gender=F, age=20]
Student [id=5, firstName=Khaled, lastName=Mohamed, gender=M, age=22]
Student [id=6, firstName=Ghada, lastName=Sarhan, gender=F, age=21]

6. Download the Source Code of this example:

This was an example of how to to Write/Read CSV Files with Apache Commons CSV.

Download
You can download the full source code of this example here: Apache Commons CSV Example Code

Ashraf Sarhan

Ashraf Sarhan is a passionate software engineer, an open source enthusiast, has a Bsc. degree in Computer and Information Systems from Alexandria University. He is experienced in building large, scalable and distributed enterprise applications/service in multiple domains. He also has a keen interest in JavaEE, SOA, Agile and Big Data technologies.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Nigel Nquande
Nigel Nquande
5 years ago

Maybe I’m missing something, but I don’t see the point of the POJO, seeing as each record is a list of Strings. Converting to and from the POJO just adds unnecessary overhead.

Back to top button