Writing a CSV file in Java using OpenCSV
Last Updated :
07 Dec, 2021
A Comma-Separated Values (CSV) file is just a normal plain-text file, store data in a column by column, and split it by a separator (e.g normally it is a comma “, ”).
OpenCSV is a CSV parser library for Java. OpenCSV supports all the basic CSV-type operations you are want to do. Java 7 is currently the minimum supported version for OpenCSV. Java language does not provide any native support for effectively handling CSV files so we are using OpenCSV for handling CSV files in Java.
How to add OpenCSV in your Project?
For maven project, you can include the OpenCSV maven dependency in pom.xml file.
xml
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>4.1</version>
</dependency>
For Gradle Project, you can include the OpenCSV dependency.
compile group: 'com.opencsv', name: 'opencsv', version: '4.1'
You can Download OpenCSV Jar and include in your project class path.
Writing a CSV File
Writing a CSV file is as simple as reading. Create an instance of CSVWriter by passing FileWriter object as parameter and start writing data to CSV file using methods of CSVWriter Class. After writing data we need to close CSVWriter connection by calling close() method of CSVWriter class.
-
Write Data Line by line - CSVWriter can write line by line using writeNext() method where a string array is passed with each comma-separated element as a separate entry.
CODE:
Java
public static void writeDataLineByLine(String filePath)
{
// first create file object for file placed at location
// specified by filepath
File file = new File(filePath);
try {
// create FileWriter object with file as parameter
FileWriter outputfile = new FileWriter(file);
// create CSVWriter object filewriter object as parameter
CSVWriter writer = new CSVWriter(outputfile);
// adding header to csv
String[] header = { "Name", "Class", "Marks" };
writer.writeNext(header);
// add data to csv
String[] data1 = { "Aman", "10", "620" };
writer.writeNext(data1);
String[] data2 = { "Suraj", "10", "630" };
writer.writeNext(data2);
// closing writer connection
writer.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Output: result.csv file with following Data
"Name", "Class", "Marks"
"Aman", "10", "620"
"Suraj", "10", "630"
-
Write all Data at once- For witting data at once call writeAll() method of CSVWriter class and pass A List of String[] as the parameter with each String[] representing a line of the file.
CODE:
Java
public static void writeDataAtOnce(String filePath)
{
// first create file object for file placed at location
// specified by filepath
File file = new File(filePath);
try {
// create FileWriter object with file as parameter
FileWriter outputfile = new FileWriter(file);
// create CSVWriter object filewriter object as parameter
CSVWriter writer = new CSVWriter(outputfile);
// create a List which contains String array
List<String[]> data = new ArrayList<String[]>();
data.add(new String[] { "Name", "Class", "Marks" });
data.add(new String[] { "Aman", "10", "620" });
data.add(new String[] { "Suraj", "10", "630" });
writer.writeAll(data);
// closing writer connection
writer.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Output: result.csv file with following Data
"Name", "Class", "Marks"
"Aman", "10", "620"
"Suraj", "10", "630"
Writing CSV File with different separator
By default, the separator for CSV will be a comma(, ). If you want to make another character as a separator so it can be passed as an argument to CSVWriter class.
Syntax :
CSVWriter(Writer writer, char separator, char quotechar,
char escapechar, String lineEnd)
Description : Constructs CSVWriter with supplied separator,
quote char, escape char and line ending.
Code:
Java
public static void writeDataForCustomSeparatorCSV(String filePath)
{
// first create file object for file placed at location
// specified by filepath
File file = new File(filePath);
try {
// create FileWriter object with file as parameter
FileWriter outputfile = new FileWriter(file);
// create CSVWriter with '|' as separator
CSVWriter writer = new CSVWriter(outputfile, '|',
CSVWriter.NO_QUOTE_CHARACTER,
CSVWriter.DEFAULT_ESCAPE_CHARACTER,
CSVWriter.DEFAULT_LINE_END);
// create a List which contains String array
List<String[]> data = new ArrayList<String[]>();
data.add(new String[] { "Name", "Class", "Marks" });
data.add(new String[] { "Aman", "10", "620" });
data.add(new String[] { "Suraj", "10", "630" });
writer.writeAll(data);
// closing writer connection
writer.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Output: result.csv file with following Data
Name|Class|Marks
Aman|10|620
Suraj|10|630
Example:
Let’s create java program which generate a semi-colon separated csv file and contains the data provided as input.
Input:
Enter no of rows
9
Enter Data
Name Class Marks
Aman 10 543
Amar 10 541
Sanjeet 10 555
Luv 10 580
Ranjeet 10 512
Rabi 10 540
Dev 10 333
Sunny 10 198
Code:
Java
// Java program to illustrate
// for Writing Data in CSV file
import java.io.*;
import java.util.*;
import com.opencsv.CSVWriter;
public class ResultGenerator {
private static final String CSV_FILE_PATH
= "./result.csv";
public static void main(String[] args)
{
addDataToCSV(CSV_FILE_PATH);
}
public static void addDataToCSV(String output)
{
// first create file object for file placed at location
// specified by filepath
File file = new File(output);
Scanner sc = new Scanner(System.in);
try {
// create FileWriter object with file as parameter
FileWriter outputfile = new FileWriter(file);
// create CSVWriter with ';' as separator
CSVWriter writer = new CSVWriter(outputfile, ';',
CSVWriter.NO_QUOTE_CHARACTER,
CSVWriter.DEFAULT_ESCAPE_CHARACTER,
CSVWriter.DEFAULT_LINE_END);
// create a List which contains Data
List<String[]> data = new ArrayList<String[]>();
System.out.println("Enter no of rows");
int noOfRow = Integer.parseInt(sc.nextLine());
System.out.println("Enter Data");
for (int i = 0; i < noOfRow; i++) {
String row = sc.nextLine();
String[] rowdata = row.split(" ");
data.add(rowdata);
}
writer.writeAll(data);
// closing writer connection
writer.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Output: result.csv file with following Data
Name;Class;Marks
Aman;10;543
Amar;10;541
Sanjeet;10;555
Luv;10;580
Ranjeet;10;512
Rabi;10;540
Dev;10;333
Sunny;10;198
In future articles, we will include more Operations on CSV file using OpenCSV.
Reference:OpenCSV Documentation,
CSVWriter class documentation
Similar Reads
Java Tutorial
Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Java OOP(Object Oriented Programming) Concepts
Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Java Interview Questions and Answers
Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands
SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 min read
Arrays in Java
Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
15+ min read
TCP/IP Model
The TCP/IP model (Transmission Control Protocol/Internet Protocol) is a four-layer networking framework that enables reliable communication between devices over interconnected networks. It provides a standardized set of protocols for transmitting data across interconnected networks, ensuring efficie
7 min read
Inheritance in Java
Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
13 min read
Java Exception Handling
Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc.An Exception is an unwanted or unexpected event that occurs during the execution of a program (i.e., at runti
10 min read
Collections in Java
Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Basics of Computer Networking
A computer network is a collection of interconnected devices that share resources and information. These devices can include computers, servers, printers, and other hardware. Networks allow for the efficient exchange of data, enabling various applications such as email, file sharing, and internet br
14 min read