To write a CSV file in Java, use the CSVWriter class from the OpenCSV library. To utilize the CSVWriter class, you may need to include the OpenCSV library in your project's dependencies. If you're using Maven, you can accomplish this by adding the below dependency to your pom.xml file:
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>5.5.1</version>
</dependency>
Example
package week1.day2;
import java.io.FileWriter;
import java.io.IOException;
import com.opencsv.CSVWriter;
public class Calculator {
public static void main(String[] args) throws IOException {
// create a FileWriter object
FileWriter writer = new FileWriter("C:\\Users\\arili\\git\\Assignments\\Selenium\\target\\Book1.csv");
//Create a CSVWriter object
CSVWriter csvWriter = new CSVWriter(writer);
// create an array of data to write
String[] data = { "Ace", "Portgas", "25" };
// write the data to the CSV file
csvWriter.writeNext(data);
// close the CSVWriter object
csvWriter.close();
}
}
- In this example, we first build a FileWriter object to write to the "Book1.csv" CSV file.
- We then use the FileWriter object to construct a CSVWriter object.
- Then, we generate an array of data to be written to the CSV file.
- In this scenario, the array comprises three components that reflect a person's first name, last name, and age.
- The data is then written to the CSV file using the CSVWriter object's writeNext function.
- Finally, we close the CSVWriter object to free whatever resources it may have.