Core Java

Write/Read CSV Files in Java Example

In this example we are going to demonstrate how to Write/Read CSV files. CSV (Comma Separated Values) is a file format for data storage which looks like a text file, contains information which is organized with one record on each line and each field is separated by comma.

A CSV file is primarily used in database migration process where we can transport data between two databases of different formats through a computer program.

There are many ways to write and read CSV files in java where we can use a native java or an open source 3rd Party tool like OpenCSV, Apache Commons CSV and Super CSV.

So, Let’s see how we can write and read a simple CSV file using the native java code.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

and many more ....

 

1. 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 + "]";
	}
}

2. 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 FileWriter class.

CsvFileWriter.java:

package com.jcg;

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

/**
 * @author ashraf
 * 
 */
public class CsvFileWriter {
	
	//Delimiter used in CSV file
	private static final String COMMA_DELIMITER = ",";
	private static final String NEW_LINE_SEPARATOR = "\n";
	
	//CSV file header
	private static final String 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;
				
		try {
			fileWriter = new FileWriter(fileName);

			//Write the CSV file header
			fileWriter.append(FILE_HEADER.toString());
			
			//Add a new line separator after the header
			fileWriter.append(NEW_LINE_SEPARATOR);
			
			//Write a new student object list to the CSV file
			for (Student student : students) {
				fileWriter.append(String.valueOf(student.getId()));
				fileWriter.append(COMMA_DELIMITER);
				fileWriter.append(student.getFirstName());
				fileWriter.append(COMMA_DELIMITER);
				fileWriter.append(student.getLastName());
				fileWriter.append(COMMA_DELIMITER);
				fileWriter.append(student.getGender());
				fileWriter.append(COMMA_DELIMITER);
				fileWriter.append(String.valueOf(student.getAge()));
				fileWriter.append(NEW_LINE_SEPARATOR);
			}

			
			
			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();
			} catch (IOException e) {
				System.out.println("Error while flushing/closing fileWriter !!!");
                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

3. Read from CSV File:

CsvFileReader reads the CSV file in java using BufferedReader class then skipping the header and starting from the second line, we split each line using String.split() function. A String.split() function splits string around matches of the given regular expression. Finally, we create a new list of student and print it.

CsvFileReader.java:

package com.jcg;

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

/**
 * @author ashraf_sarhan
 *
 */
public class CsvFileReader {
	
	//Delimiter used in CSV file
	private static final String COMMA_DELIMITER = ",";
	
	//Student attributes index
	private static final int STUDENT_ID_IDX = 0;
	private static final int STUDENT_FNAME_IDX = 1;
	private static final int STUDENT_LNAME_IDX = 2;
	private static final int STUDENT_GENDER = 3; 
	private static final int STUDENT_AGE = 4;
	
	public static void readCsvFile(String fileName) {

		BufferedReader fileReader = null;
     
        try {
        	
        	//Create a new list of student to be filled by CSV file data 
        	List students = new ArrayList();
        	
            String line = "";
            
            //Create the file reader
            fileReader = new BufferedReader(new FileReader(fileName));
            
            //Read the CSV file header to skip it
            fileReader.readLine();
            
            //Read the file line by line starting from the second line
            while ((line = fileReader.readLine()) != null) {
                //Get all tokens available in line
                String[] tokens = line.split(COMMA_DELIMITER);
                if (tokens.length > 0) {
                	//Create a new student object and fill his  data
					Student student = new Student(Long.parseLong(tokens[STUDENT_ID_IDX]), tokens[STUDENT_FNAME_IDX], tokens[STUDENT_LNAME_IDX], tokens[STUDENT_GENDER], Integer.parseInt(tokens[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();
            } catch (IOException e) {
            	System.out.println("Error while closing fileReader !!!");
                e.printStackTrace();
            }
        }

	}

}

4. 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]

5. Download the Source Code of this example:

This was an example of how to to Write/Read CSV files.

Download
You can download the full source code of this example here: Write/Read CSV Files Example Code

Want to know how to develop your skillset to become a Java Rockstar?

Join our newsletter to start rocking!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions

 

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.

9 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
George Shapiro
George Shapiro
5 years ago

Now try it with data containing newlines and embedded commas.

Sourov
Sourov
5 years ago

Thanks for your blog. It helped me a lot. Can you help me to solve the problem of parsing a CSV cell which contains multiple comma(,)?

sunil
sunil
5 years ago

where file will get store after writing successfully .

sumit sain
sumit sain
4 years ago

thanks

jot
jot
4 years ago

where file will get store after writing successfully .

Shaikh Sanah
Shaikh Sanah
2 years ago

I’m facing Type mismatch error
for (Student student : students)

nivedita
nivedita
2 years ago
Reply to  Shaikh Sanah

i’m facing the same issue

max
max
1 year ago
Reply to  Shaikh Sanah

same here

Sravya
Sravya
11 months ago
Reply to  max

List<Student> students =

new ArrayList();
This will work

Back to top button