
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
Download the binaries/jars from http://sourceforge.net/projects/opencsv/
Download through maven by updating pom.xml as
<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"