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
Reading a CSV file in Java using OpenCSV
A Comma-Separated Values (CSV) file is just a normal plain-text file, store data in 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 th
7 min read
How to Write JSON Array to CSV File using Java?
We will see how to read a JSONArray from a JSON file and write the contents to a CSV file using Java. JavaScript Object Notation (JSON) is a standard text-based format for representing structured data that is based on JavaScript object syntax. It is commonly used for transmitting data in web applica
3 min read
Reading and Writing Data to Excel File in Java using Apache POI
In Java, reading an Excel file is not similar to reading a Word file because of cells in an Excel file. JDK does not provide a direct API to read data from Excel files for which we have to toggle to a third-party library that is Apache POI. Apache POI is an open-source java library designed for read
5 min read
Mapping Java Beans to CSV Using OpenCSV
The need to convert Java Beans(Objects) to CSV file arises very commonly and there are many ways to write Bean into CSV file but one of the best ways to map java bean to CSV is by using OpenCSV Library. In OpenCSV there is a class name StatefulBeanToCsvBuilder which helps to convert Java Beans to CS
4 min read
Java.io.StringWriter class in Java
Java StringWriter class creates a string from the characters of the String Buffer stream. Methods of the StringWriter class in Java can also be called after closing the Stream as this will raise no IO Exception. Declaration in Java StringWriter Classpublic class StringWriter extends WriterConstructo
6 min read
How to Write to a File Using Applet?
In this article, we will learn how to write a file using Applet and grant access to write files using Applet. ApproachThe applet output window contains three fields. Those are the file name field, Text area field, and save button field. File name field: It asks the user to enter the file name to wri
3 min read
Opening Existing Excel sheet in Java using Apache POI
Apache POI is a powerful API by which one can read, write and modify any Microsoft document like powerpoint, world, or excel. Apache POI have different classes and method to work upon different MS Office Document. POIFS -It's Stand for "Poor Obfuscation Implementation File System". This component i
2 min read
Convert byte[] array to File using Java
As we know whenever it comes to writing over a file, write() method of the File class comes into play but here we can not use it in order to convert that byte into a file. In order to convert a byte array to a file, we will be using a method named the getBytes() method of String class. Implementatio
3 min read
Spring Boot Batch Processing Using Spring Data JPA to CSV File
The Spring Batch is a framework in the Spring Boot ecosystem It can provide a lot of functionalities for Batch processing. The Spring Batch framework simplifies the batch development of applications by providing reliable components and other patterns for common batch processing concerns. Mostly, bat
7 min read
Redirecting System.out.println() Output to a File in Java
System.out.println()Â is used mostly to print messages to the console. However very few of us are actually aware of its working mechanism. We can use System.out.println() to print messages to other sources too, not just restricting it to the console. However, before doing so, we must reassign the st
2 min read