java

How to export data to CSV file in Java

In this tutorial, we are going to see how to write or export data to a CSV file in Java.

A CSV (Comma-Separated Values) file is just a regular text file, which stores data column by column and divides it by separators (commas).
 

Example: The Book class

The Book class contains details of books such as title, author, and year of publication.

class Book
{
    public String title;
    public String author;
    public int year;
    
    public Book(String title,String author,int year)
    {   this.title=title;
        this.author=author;
        this.year=year;
    }
    public String getTitle()
    {
        return title;
    }
     public String getAuthor()
    {
        return author;
    }
    public int getYear()
    {
        return year;
    }
    public void setTitle(String title)
    {
        this.title=title;
    }
     public void setAuthor(String author)
    {
       this.author=author;
    }
    public void setYear(int year)
    {
        this.year=year;
    }
    @Override
    public String toString() {
        return "Book [title="+title+", author="+author+", year="+year+"]";
    }
}
 

Write into CSV file

We are going to use the FileWriter class to export our Book object to “Book.csv”.

import java.io.*;
import java.util.*;

public class Main 
{
	//Delimiters that must be in the CSV file
	private static final String DELIMITER = ",";
	private static final String SEPARATOR = "\n";
    
    //File header
    private static final String HEADER = "Title,Author,Year";
    
    public static void main(String args[])
    {
    	//Create new objects
    	Book book1 = new Book("Darkness to Light", "Lamar Odam", 1992);
    	Book book2 = new Book("We Are Displaced", "Malala Yousafzai", 1981);
    	Book book3 = new Book("I Am Malala", "Christina Lamb", 1978);
    	Book book4 = new Book("Girl Women", "Satyarth Nayak", 1966);
    	Book book5 = new Book("Forgotten Past", "Peter Baker", 1971);

    	//Add objects to the list
    	List bookList = new ArrayList();
    	bookList.add(book1);
    	bookList.add(book2);
    	bookList.add(book3);
    	bookList.add(book4);
    	bookList.add(book5);
    	
    	FileWriter file = null;
    	
    	try
    	{
    		file = new FileWriter("Book.csv");
    		//Add header
    		file.append(HEADER);
    		//Add a new line after the header
    		file.append(SEPARATOR);
    		//Iterate through bookList
    		Iterator it = bookList.iterator();
    		while(it.hasNext())
    		{
    			Book b = (Book)it.next();
    			file.append(b.getTitle());
    			file.append(DELIMITER);
    			file.append(b.getAuthor());
    			file.append(DELIMITER);
    			file.append(String.valueOf(b.getYear()));
    			file.append(SEPARATOR);
    		}
			
    		file.close();
    	}
    	catch(Exception e)
    	{
    		e.printStackTrace();
    	}
    }
}

Output:

Title,Author,Year
Darkness to Light,Lamar Odam,1992
We Are Displaced,Malala Yousafzai,1981
I Am Malala,Christina Lamb,1978
Girl Women,Satyarth Nayak,1966
Forgotten Past,Peter Baker,1971
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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