Writing a CSV file in Java using OpenCSV


In Java there is no delegate library or API in order to write or read comma separated value(csv) file.So a 3rd party APIs are available for such requirements.Most popular 3rd party API is OpenCSV which is provide methods to deal with CSV file such as read csv file,write csv file,parse values of csv file,mapping of csv file values to java beans and java beans to csv file etc.

In order to use/import this tool in Java project there are following approaches −

<dependency>
   <groupId>net.sf.opencsv</groupId>
   <artifactId>opencsv</artifactId>
   <version>2.3</version>
</dependency>

Take a glance of this tool how it is helpful in context of writing csv file in Java.CSVWriter class of OpenCSV is primarily used to write csv file.

Example

import au.com.bytecode.opencsv.CSVWriter;
public class CSVFile WriterDemo {
   public static void main(String[] args) throws Exception {
      String csv = "myCSV.csv";
      CSVWriter writer = new CSVWriter(new FileWriter(csv));
      String [] record = "Emp004,James,Miller,North Pole Street,Newyork".split(",");
      writer.writeNext(record);
      writer.close();
   }
}

Output

myCSV.csv file created with following text

"Emp004", "James", "Miller", "North Pole Street", "Newyork"

Updated on: 25-Jun-2020

546 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements