Writing Data Into CSV File Using Java

JavaJavaBeginner
Practice Now

Introduction

In this lab, you will learn how to write data to a CSV file using Java programming language. You will use the OpenCSV library to perform the write operation. By the end of this lab, you will know how to write simple data to a CSV file and how to append data to an existing CSV file.

Add the library dependencies

Before we start writing data to a CSV file, we need to import the OpenCSV library into our project. You can download the JAR file from the OpenCSV website or add the following dependency to your pom.xml file:

<dependency>
	<groupId>com.opencsv</groupId>
	<artifactId>opencsv</artifactId>
	<version>5.4</version>
</dependency>

Create a CSVWriter object

To write data to a CSV file, we need to create a CSVWriter object and pass a FileWriter object with the file name to the CSVWriter constructor. For example, to write data to a file named students.csv, we can use the following code snippet:

CSVWriter writer = new CSVWriter(new FileWriter("students.csv"));

Write Data to the CSV file

After creating the CSVWriter object, we can use the writeNext() method of the CSVWriter class to write data to the CSV file. writeNext() method takes a string array as a parameter that represents each row in the CSV file. Each element of the array represents a field in the CSV record.

// This code block writes data to CSV file
String[] record = {"John","Doe","[email protected]"};
writer.writeNext(record);

Append Data to an Existing CSV File

To append data to an existing CSV file, we need to create the CSVWriter object in append mode by passing true to the FileWriter constructor. For example, to append data to an existing file named students.csv, we can use the following code:

CSVWriter writer = new CSVWriter(new FileWriter("students.csv", true));

Close the CSV Writer

After writing data to the CSV file, it's essential to close the CSV writer to release the file resources. We can use the close() method of the CSVWriter class to close the file.

writer.close();

Summary

In this lab, you learned how to write data to a CSV file using Java programming language. You learned how to create a CSVWriter object using the OpenCSV library, write data to a CSV file, and append data to an existing CSV file. Finally, you learned how to close the CSV writer to release the file resources. Remember to keep the code and comments concise and clear.

Other Java Tutorials you may like