• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

How to Read/Parse/Write CSV File using OpenCSV

January 21, 2016 by javainterviewpoint Leave a Comment

CSV stands for Comma Seperated Values, it is the popular format used for import and exporting of data. Java by default doesn’t provide a parser for CSV hence at the end we will end up writing up a parser. OpenCSV is a third party library which can effecitively handle a CSV file. In this article we will learn how to read a CSV file and how to write data to a CSV file using OpenCSV.

OpenCSV Dependency

We will be requiring the below jars to be put in the class path for performing the Read/Write operations

  • opencsv-3.6.jar
  • commons-lang3-3.4.jar

Employee.csv

Lets assume we are reading the Employee.csv file which has the contents like below

EmployeeID,FirstName,LastName,Salary
1,FirstName1,LastName1,10000
2,FirstName2,LastName2,20000
3,FirstName3,LastName3,30000
4,FirstName4,LastName4,40000
5,FirstName5,LastName5,50000

Reading a CSV File using OpenCSV

OpenCSV is a Third party library, it gives better handling to parse a CSV file, we will be using CSVReader class to read the CSV File

package com.javainterviewpoint;

import java.io.FileReader;
import java.util.Arrays;

import com.opencsv.CSVReader;

public class ReadCSV_OpenCSV 
{
	public static void main(String args[])
    {
        CSVReader csvReader = null;
        
        try
        {
            /**
             * Reading the CSV File
             * Delimiter is comma
             * Start reading from line 1
             */
            csvReader = new CSVReader(new FileReader("Employee.csv"),',','"',1);
            //employeeDetails stores the values current line
            String[] employeeDetails = null;
            while((employeeDetails = csvReader.readNext())!=null)
            {
            	//Printing to the console
            	System.out.println(Arrays.toString(employeeDetails));
            }
        }
        catch(Exception ee)
        {
            ee.printStackTrace();
        }
        finally
        {
		try
		{
			//closing the reader
			csvReader.close();
		}
		catch(Exception ee)
		{
			ee.printStackTrace();
		}
	}
    }
}

Output :

[1, FirstName1, LastName1, 10000]
[2, FirstName2, LastName2, 20000]
[3, FirstName3, LastName3, 30000]
[4, FirstName4, LastName4, 40000]
[5, FirstName5, LastName5, 50000]

In the above example we have read the file line by line, we can use the readAll() method, to read all the rows in a single shot. This method returns a List object back, once read we can iterate over the list like below.

readAll() Method

package com.javainterviewpoint;

import java.io.FileReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.opencsv.CSVReader;

public class ReadCSV_OpenCSV 
{
	public static void main(String args[])
    {
        CSVReader csvReader = null;
        
        try
        {
            /**
             * Reading the CSV File
             * Delimiter is comma
             * Start reading from line 1
             */
            csvReader = new CSVReader(new FileReader("Employee.csv"),',','"',1);
            //employeeDetails stores the values current line
            String[] employeeDetails = null;
            //List for holding all the rows
            List<String[]> rows = new ArrayList<String[]>();
            rows = csvReader.readAll();
            //Read individual row from List of rows
            for(String[] row : rows)
            {
            	System.out.println(Arrays.toString(row));
            }
        }
        catch(Exception ee)
        {
            ee.printStackTrace();
        }
        finally
        {
		try
		{
			//closing the reader
			csvReader.close();
		}
		catch(Exception ee)
		{
			ee.printStackTrace();
		}
	}
    }
}

Writing data to a new CSV File

Here we will be using CSVWriter class to export the data into CSV format.

package com.javainterviewpoint;

import java.io.FileWriter;

import com.opencsv.CSVWriter;

public class WriteCSV_OpenCSV 
{
	public static void main(String args[])
	{
		CSVWriter csvWriter = null;
		try
		{
			//Create CSVWriter for writing to Employee.csv 
			csvWriter = new CSVWriter(new FileWriter("Employee.csv"));
			//row1
			String[] row = new String[]{"6","FirstName6","LastName6","60000"};
			csvWriter.writeNext(row);
			//row2
			row = new String[]{"7","FirstName7","LastName7","70000"};
			csvWriter.writeNext(row);
		}
		catch(Exception ee)
		{
			ee.printStackTrace();
		}
		finally
		{
			try
			{
				//closing the writer
				csvWriter.close();
			}
			catch(Exception ee)
			{
				ee.printStackTrace();
			}
		}
	}
}

Output :

When we open the Employee.csv file we can find the below content written on to it

"6","FirstName6","LastName6","60000"
"7","FirstName7","LastName7","70000"

Appending to the existing CSV File

The above method will be creating a new CSV file everytime, but many times what we want is to append to the exisiting content. This can be done by passing a boolean argument to the FileWriter instance. If true contents will be appended. If false contents will be replaced.

package com.javainterviewpoint;

import java.io.FileWriter;

import com.opencsv.CSVWriter;

public class WriteCSV_OpenCSV 
{
	public static void main(String args[])
	{
		CSVWriter csvWriter = null;
		try
		{
			//Create CSVWriter for writing to Employee.csv 
			csvWriter = new CSVWriter(new FileWriter("Employee.csv",true));
			//row1
			String[] row = new String[]{"6","FirstName6","LastName6","60000"};
			csvWriter.writeNext(row);
			//row2
			row = new String[]{"7","FirstName7","LastName7","70000"};
			csvWriter.writeNext(row);
		}
		catch(Exception ee)
		{
			ee.printStackTrace();
		}
		finally
		{
			try
			{
				//closing the writer
				csvWriter.close();
			}
			catch(Exception ee)
			{
				ee.printStackTrace();
			}
		}
	}
}

Output :

Now when you open the Employee.csv we will have our content appended to the existing

"6","FirstName6","LastName6","60000"
"7","FirstName7","LastName7","70000"
"8","FirstName8","LastName8","80000"
"9","FirstName9","LastName9","90000"

Usage of writeAll() Method

In the above examples we wrote line by line only, suppose if you want to write huge data in a single shot then we can use the writeAll() method for it.

package com.javainterviewpoint;

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

import com.opencsv.CSVWriter;

public class WriteCSV_OpenCSV 
{
	public static void main(String args[])
	{
		CSVWriter csvWriter = null;
		try
		{
			//Create CSVWriter for writing to Employee.csv 
			csvWriter = new CSVWriter(new FileWriter("Employee.csv",true));
			//List of rows to be written
			List<String[]> rows = new ArrayList<String[]>();
			rows.add(new String[]{"10","FirstName10","LastName10","100000"});
			rows.add(new String[]{"11","FirstName11","LastName11","110000"});
			rows.add(new String[]{"12","FirstName12","LastName12","120000"});
			rows.add(new String[]{"13","FirstName13","LastName13","130000"});
			//Writing list of rows to the csv file
			csvWriter.writeAll(rows);
		}
		catch(Exception ee)
		{
			ee.printStackTrace();
		}
		finally
		{
			try
			{
				//closing the writer
				csvWriter.close();
			}
			catch(Exception ee)
			{
				ee.printStackTrace();
			}
		}
	}
}

Output :

In theEmployee.csv list of rows will be appended

"6","FirstName6","LastName6","60000"
"7","FirstName7","LastName7","70000"
"8","FirstName8","LastName8","80000"
"9","FirstName9","LastName9","90000"
"10","FirstName10","LastName10","100000"
"11","FirstName11","LastName11","110000"
"12","FirstName12","LastName12","120000"
"13","FirstName13","LastName13","130000"

Other interesting articles which you may like …

  • CsvToBean and BeanToCsv Example – Using OpenCSV
  • How to Read Excel File in Java using POI
  • How to Write Excel File in Java using POI
  • JAXB Tutorial – What is JAXB
  • JAXB Marshalling Example – Convert Java Object to XML in Java
  • JAXB UnMarshalling Example – Convert XML to Java Object
  • How to Convert Java Object to JSON using JAXB

Filed Under: Core Java, Java Tagged With: CSV, CSV File, How to, OpenCSV, Parse, Read, Write

Leave a Reply Cancel reply

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

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

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·