Signup/Sign In

How to write data into CSV File

In this post, we are going to learn to write data into a CSV file using Java code. In our previous post, we learned to read data from the CSV file. You can refer to this post here "Read CSV in JAVA".

To write data into the CSV file, we are using OpenCSV library which is a third-party library. So, you must download the JARs from the here. Dowload OpenCSV JARs.

After downloading the JARs import them into your project. This library contains two important class CSVReader and CSVWriter that are used to read and write operations in the CSV file.

Here, we are using CSVWriter class to write data into the CSV file students.csv.

Time for an Example:

Let's create an example to write data into a CSV file. Here, we want to write four records to the students.csv file. So, we used writeNext() method of CSVWriter class to write the data.

import java.io.FileWriter;
import java.io.IOException;

import com.opencsv.CSVWriter;

public class Main {
	public static void main(String[] args) throws IOException{  
		String csvFile = "students.csv";
		CSVWriter cw = new CSVWriter(new FileWriter(csvFile));
		String line1[] = {"Id", "Name", "Country"};
		String line2[] = {"1", "Sohan", "India"};
		String line3[] = {"2", "Rohan", "USA"};
		String line4[] = {"3", "Abhishek", "UK"};
		//Writing data to the csv file
		cw.writeNext(line1);
		cw.writeNext(line2);
		cw.writeNext(line3);
		cw.writeNext(line4);
		//close the file
		cw.close();
	}
}

After successfully executing the above code, the students.csv file will have the below data.

//students.csv

"Id","Name","Country"
"1","Sohan","India"
"2","Rohan","USA"
"3","Abhishek","UK"

Time for another Example: Append the CSV

Let's take another example to write the CSV file. Here, we are opening the CSV file in append mode to write the data. The benefit of append mode is, it does not replace the old data of the file. To enable the append mode, use the true literal in the FilWriter() constructor as we did in the below example.

import java.io.FileWriter;
import java.io.IOException;

import com.opencsv.CSVWriter;

public class Main {
	public static void main(String[] args) throws IOException{  
		String csvFile = "students.csv";
		CSVWriter cw = new CSVWriter(new FileWriter(csvFile,true));
		String[] line = {"4", "David", "USA"};
		//Writing data to the csv file
		cw.writeNext(line);
		//close the file
		cw.close();
	}
}

See, we wrote a single entry to the file and it is written at the end of the file which means our code working fine.

// student.csv

"Id","Name","Country"
"1","Sohan","India"
"2","Rohan","USA"
"3","Abhishek","UK"
"4","David","USA"



About the author:
I am a 3rd-year Computer Science Engineering student at Vellore Institute of Technology. I like to play around with new technologies and love to code.