A “Comma-Separated Values or CSV” file simply stores data in a column-by-column format within a normal plain-text file and splits/separates it using a specified separator (typically a comma ‘,’). While working with file handling and file manipulation tasks, Java developers often come across a situation where they need to write data to a CSV file. In such situations, they can use different built-in classes and third-party libraries that will be discussed in this post with suitable examples.
This post illustrates how to write data to a CSV file in Java using Java FileWriter Class, Java PrintWriter Class, Java BufferedWriter Class, OpenCSV Library, and Apache Commons CSV library.
Let’s begin with the PrintWriter Class.
1) Writing Data to a CSV File Using Java FileWriter Class
The Java FileWriter class belongs to the “java.io” package that lets us write character data to a file. Using this class we can easily write data to a CSV file, as shown in the following code:
import java.io.*;
public class WriteDataCSV {
public static void main(String[] args) {
try {
FileWriter obj = new FileWriter("C:\\Users\\HP\\Desktop\\sampleFile.txt");
obj.write("empName, empDesig, empAge\n");
obj.write("Ambrose, Author, 25\n");
obj.write("Joseph, Designer, 27\n");
obj.write("Alexa, Tutor, 30\n");
obj.close();
} catch (IOException excep) {
excep.printStackTrace();
}
}
}
Code Explanation
- First, we import the required classes like FileWriter and IOException to write data to a CSV file by avoiding any potential exceptions.
- We use the FIleWriter() constructor to specify the file’s path to which we want to write data.
- After this, we invoke the write() method of the FileWriter class to write the data into the selected CSV class.
Output (sampleFile.txt)
2) Writing Data to a CSV File Using Java BufferedWriter Class
The BufferedWriter is a built-in Java class that belongs to the same “io” package. This class lets us write text to a character-output stream with buffering. Using this class, you can write data to any CSV file:
import java.io.*;
public class WriteDataCSV {
public static void main(String[] args) {
try {
BufferedWriter obj = new BufferedWriter(new FileWriter("C:\\Users\\HP\\Desktop\\sampleFile.txt"));
obj.write("empName, empDesig, empSal\n");
obj.write("Ambrose, Author, 25000\n");
obj.write("Joseph, Designer, 25000\n");
obj.write("Alexa, Tutor, 30000\n");
obj.close();
} catch (IOException excep) {
excep.printStackTrace();
}
}
}
Code Explanation:
- In this example, we wrap the FileWriter() constructor within the BufferedWriter() constructor. While the FileWriter() constructor is initialized with the file path (to which the data will be written).
- After this, we use the object of the BufferedWriter class to invoke the write() method to write the data to the CSV file
Output (sampleFile.txt)
3) Writing Data to a CSV File Using Java PrintWriter Class
The PrintWriter is an in-built class of Java’s io package that helps us print the formatted representation of objects to a text-output stream. You can use this class to write data to a CSV file, as demonstrated in the following code:
import java.io.*;
public class WriteDataCSV {
public static void main(String[] args) {
try {
PrintWriter obj = new PrintWriter(new File("C:\\Users\\HP\\Desktop\\sampleFile.txt"));
StringBuffer fileHeader = new StringBuffer("");
StringBuffer fileData = new StringBuffer("");
fileHeader.append( "empName, empDesig, empSal\n");
obj.write(fileHeader.toString());
fileData.append("Ambrose");
fileData.append(',');
fileData.append("Tutor");
fileData.append(',');
fileData.append("25000");
fileData.append('\n');
fileData.append("Joseph");
fileData.append(',');
fileData.append("Designer");
fileData.append(',');
fileData.append("30000");
fileData.append('\n');
obj.write(fileData.toString());
obj.close();
} catch (FileNotFoundException excep) {
excep.printStackTrace();
}
}
}
Code Explanation
- We use the PrintWriter() constructor along with the File() constructor to specify the file path to which we want to write the data.
- Next, we create two objects of the StringBuffer class to store the file header and file’s data, respectively.
- Next, we use the append() method to append the header line and the content of the file to the respective StringBuffer object.
- Finally, the write() method is used to write the file header and the file content to the selected CSV file.
Output (sampleFile.txt)
4) Writing Data to a CSV File in Java Using OpenCSV
It is a third-party library that can also be used to write data to a CSV file. To do that, first, add the given dependency to the xml file of your Maven project:
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>5.9</version>
</dependency>
Once added, you can write data to a CSV file line-by-line or all data at once.
Example 1: Writing Data to a CSV File Line-by-line Using OpenCSV
In the following example, first, we import the CSVWrite class from the OpenCSV:
import java.io.*;
import com.opencsv.CSVWriter;
public class WriteDataCSV {
public static void main(String[] args) {
File fileObj = new File("C:\\Users\\HP\\Desktop\\sampleFile.txt");
try {
FileWriter resultFile = new FileWriter(fileObj);
CSVWriter csvWriterObj = new CSVWriter(resultFile);
String[] fileHeader = { "empName", "empDesig", "empSal" };
csvWriterObj.writeNext(fileHeader);
String[] emp1 = { "John", "Tutor", "35000" };
csvWriterObj.writeNext(emp1);
String[] emp2 = { "Joseph", "Instructor", "35000" };
csvWriterObj.writeNext(emp2);
String[] emp3 = { "Alex", "Software Engineer", "40000" };
csvWriterObj.writeNext(emp3);
String[] emp4 = { "Seth", "Designer", "30000" };
csvWriterObj.writeNext(emp4);
String[] emp5 = { "Ambrose", "Instructor", "35000" };
csvWriterObj.writeNext(emp5);
System.out.println("Data Written to the CSV File Successfully"); csvWriterObj.close();
}
catch (IOException excep) {
excep.printStackTrace();
}
}
}
Code Explanation
- First, we create an object of the FilerWriter class to write data to the selected CSV file.
- Also, we create an object of the CSVWriter class to write the CSV formatted data to the selected CSV file.
- Next, we define a string array to specify the column names(file header). We use the WriteNext() method to write the specified column names as the first row of the selected CSV file.
- After this, we create multiple arrays to specify the data of different employees and invoke the writeNext() method on each array to write it to the CSV file.
Output (sampleFile.txt)
Example 2: Writing All Data at Once to a CSV File Using OpenCSV
The following code demonstrates how to write all data at once to a CSV file using the OpenCSV library:
import com.opencsv.CSVWriter;import java.io.*;
import java.util.*;
public class WriteDataCSV {
public static void main(String[] args) {
File fileObj = new File("C:\\Users\\HP\\Desktop\\sampleFile.txt");
try {
FileWriter resultFile = new FileWriter(fileObj);
CSVWriter csvWriterObj = new CSVWriter(resultFile);
List<String[]> writeData = new ArrayList<String[]>();
writeData.add(new String[] {"empName", "empDesig", "empSal"});
writeData.add(new String[] {"John", "Tutor", "35000"});
writeData.add(new String[] {"Alex", "Software Engineer", "40000"});
writeData.add(new String[] {"Seth", "Designer", "30000"});
csvWriterObj.writeAll(writeData);
csvWriterObj.close();
}
catch (IOException excep) {
excep.printStackTrace();
}
}
}
Output (sampleFile.txt)
- In this example, we create a list of string arrays, and add them to a list named “writeData”.
- After this, we invoke the writeAll() method to write all the data to the selected CSV file in one go (instead of writing it line-by-line).
5) Writing Data to a CSV File in Java Using Apache Commons CSV
Apache Commons is another well-known third-party library that allows us to write data to a CSV file. However, to use Apache Commons, first, you must add the latest version of this library into the “pom.xml” file of your Maven project:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-csv</artifactId>
<version>1.10.0</version>
</dependency>
Once the library is added, import the CSVFormat and CSVPrinter classes to your Java program, as shown below:
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
public class WriteDataCSV {
public static void main(String[] args){
try {
BufferedWriter resultFile = Files.newBufferedWriter(Paths.get("C:\\Users\\HP\\Desktop\\sampleFile.txt"));
CSVPrinter csvPrinterObj = new CSVPrinter(resultFile,
CSVFormat.DEFAULT.withHeader("empName", "empDesig", "empSal"));
csvPrinterObj.printRecord("John", "Tutor", "35000");
csvPrinterObj.printRecord("Alex", "Software Engineer", "40000");
csvPrinterObj.printRecord("Seth", "Designer", "30000");
csvPrinterObj.printRecord(Arrays.asList("Alexa", "Jr. Software Engineer", "30000"));
csvPrinterObj.flush();
csvPrinterObj.close();
}
catch (IOException excep) {
excep.printStackTrace();
}
}
}
Code Explanation:
- After importing the required classes, we create a BufferedWriter to specify the file path.
- Next, we create an object of the CSVPrint class to set the header line and content of the CSV file.
- To set the header line we invoke the withHeader() method and specify the file’s content we use the printRecord() method.
- Finally, we flush the buffer before closing the writer.
Output (sampleFile.txt)
How to Write/Append Data into an Existing CSV File in Java?
To write data into an existing CSV file in Java, you must use a method that lets you append data into a file without overwriting the original content. For instance, you can use the FileWriter instance and specify the append mode as its second argument, as follows:
import java.io.*;
public class WriteDataCSV {
public static void main(String[] args) {
try {
FileWriter obj = new FileWriter("C:\\Users\\HP\\Desktop\\sampleFile.txt", true);
obj.write("Ambrose, Author, 25\n");
obj.close();
} catch (IOException excep) {
excep.printStackTrace();
}
}
}
Code Explanation:
- We create a FileWriter object and initialize it with the targeted CSV file’s path.
- We specify “true” as a second parameter to the FileWrite() method; this means the targeted CSV file will be open in “append” mode.
- Finally, we use the write() method to append a new line to an already-existing file.
The output demonstrates that this time a new line is appended(instead of overwriting) at the end of the selected file:
That’s all about writing data to a CSV file in Java.
Final Thoughts
You can use different built-in classes like FileWriter, PrintWriter, or BufferedWriter to write data to a CSV file in Java. Besides these built-in classes, you can also use some third-party libraries like Apache Commons and OpenCSV to write data to a CSV file. Using OpenCSV, you can write data line-by-line or all data at once. All these methods allow you to write data to a CSV file conveniently and efficiently. To write data into an existing CSV file in Java, you must use a method that lets you append data into a file without overwriting the original content.