OpenCSV is a lightweight java CSV parser. Today we will look into OpenCSV example for CSV parsing.
OpenCSV
OpenCSV provides most of the basic features for CSV parsing. OpenCSV is more popular because we don’t have any builtin CSV parser in java. Some of the important classes in OpenCSV CSV parser are;
CSVReader
: This is the most important class in OpenCSV. CSVReader class is used to parse CSV files. We can parse CSV data line by line or read all data at once.CSVWriter
: CSVWriter class is used to write CSV data to Writer implementation. You can define custom delimiter as well as quotes.CsvToBean
: CsvToBean is used when you want to convert CSV data to java objects.BeanToCsv
: BeanToCsv is used to export Java beans to CSV file.
OpenCSV Maven Dependency
You can add OpenCSV jar using below maven dependency.
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>3.8</version>
</dependency>
Before we start looking at example program, we require demo CSV data and corresponding java bean.
Here is our sample CSV file emps.csv
1,Pankaj Kumar,20,India
2,David Dan,40,USA
3,Lisa Ray,28,Germany
Below is our java bean class to hold CSV data.
package com.journaldev.csv.model;
public class Employee {
private String id;
private String name;
private String age;
private String country;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
@Override
public String toString() {
return "{" + id + "::" + name + "::" + age + "::" + country + "}";
}
}
Let’s look at some common example of CSV parsing and CSV writing.
CSVReader
Our first CSVReader example is to read CSV file lines one by one and then convert to list of Employee.
package com.journaldev.csv.opencsv.parser;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.journaldev.csv.model.Employee;
import com.opencsv.CSVReader;
/**
* OpenCSV CSVReader Example, Read line by line
*
* @author pankaj
*
*/
public class OpenCSVReaderLineByLineExample {
public static void main(String[] args) throws IOException {
CSVReader reader = new CSVReader(new FileReader("emps.csv"), ',');
List<Employee> emps = new ArrayList<Employee>();
// read line by line
String[] record = null;
while ((record = reader.readNext()) != null) {
Employee emp = new Employee();
emp.setId(record[0]);
emp.setName(record[1]);
emp.setAge(record[2]);
emp.setCountry(record[3]);
emps.add(emp);
}
System.out.println(emps);
reader.close();
}
}
Above CSVReader example is simple to understand. One important point is to close CSVReader to avoid memory leak. Also we can specify the delimiter character, just in case you are using something else.
Next CSVReader example is to read all the data in one shot using CSVReader readAll()
method.
package com.journaldev.csv.opencsv.parser;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.journaldev.csv.model.Employee;
import com.opencsv.CSVReader;
/**
* OpenCSV CSVReader Example, Read all at once
*
* @author pankaj
*
*/
public class OpenCSVReaderReadAllExample {
public static void main(String[] args) throws IOException {
CSVReader reader = new CSVReader(new FileReader("emps.csv"), ',');
List<Employee> emps = new ArrayList<Employee>();
List<String[]> records = reader.readAll();
Iterator<String[]> iterator = records.iterator();
while (iterator.hasNext()) {
String[] record = iterator.next();
Employee emp = new Employee();
emp.setId(record[0]);
emp.setName(record[1]);
emp.setAge(record[2]);
emp.setCountry(record[3]);
emps.add(emp);
}
System.out.println(emps);
reader.close();
}
}
CsvToBean
We want to convert CSV to java object most of the time. We can use CsvToBean in these cases. Below is a simple example showing how to convert our employee CSV file to list of Employee objects.
package com.journaldev.csv.opencsv.parser;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import com.journaldev.csv.model.Employee;
import com.opencsv.CSVReader;
import com.opencsv.bean.ColumnPositionMappingStrategy;
import com.opencsv.bean.CsvToBean;
import com.opencsv.bean.HeaderColumnNameMappingStrategy;
public class OpenCSVParseToBeanExample {
public static void main(String[] args) throws IOException {
CSVReader reader = new CSVReader(new FileReader("emps.csv"), ',');
ColumnPositionMappingStrategy<Employee> beanStrategy = new ColumnPositionMappingStrategy<Employee>();
beanStrategy.setType(Employee.class);
beanStrategy.setColumnMapping(new String[] {"id","name","age","country"});
CsvToBean<Employee> csvToBean = new CsvToBean<Employee>();
List<Employee> emps = csvToBean.parse(beanStrategy, reader);
System.out.println(emps);
}
}
ColumnPositionMappingStrategy
is used to map the CSV data row index to the Employee object fields.
Sometimes our CSV file has header data too, for example we can have emps1.csv
as below.
ID,NAME,age, country
1,Pankaj Kumar,20,India
2,David Dan,40,USA
3,Lisa Ray,28,Germany
In this case we can use HeaderColumnNameMappingStrategy
as MappingStrategy implementation. Below is the method showing HeaderColumnNameMappingStrategy usage.
// returning list of Employee for CSVWriter example demo data
public static List<Employee> parseCSVWithHeader() throws IOException {
CSVReader reader = new CSVReader(new FileReader("emps1.csv"), ',');
HeaderColumnNameMappingStrategy<Employee> beanStrategy = new HeaderColumnNameMappingStrategy<Employee>();
beanStrategy.setType(Employee.class);
CsvToBean<Employee> csvToBean = new CsvToBean<Employee>();
List<Employee> emps = csvToBean.parse(beanStrategy, reader);
System.out.println(emps);
reader.close();
return emps;
}
CSVWriter
Let’s have a look at CSVWriter example to write java objects to CSV a Writer. We will reuse parseCSVWithHeader()
defined above.
package com.journaldev.csv.opencsv.parser;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.journaldev.csv.model.Employee;
import com.opencsv.CSVWriter;
public class OpenCSVWriterExample {
public static void main(String[] args) throws IOException {
StringWriter writer = new StringWriter();
//using custom delimiter and quote character
CSVWriter csvWriter = new CSVWriter(writer, "https://www.journaldev.com/12014/#", ''');
List<Employee> emps = OpenCSVParseToBeanExample.parseCSVWithHeader();
List<String[]> data = toStringArray(emps);
csvWriter.writeAll(data);
csvWriter.close();
System.out.println(writer);
}
private static List<String[]> toStringArray(List<Employee> emps) {
List<String[]> records = new ArrayList<String[]>();
// adding header record
records.add(new String[] { "ID", "Name", "Age", "Country" });
Iterator<Employee> it = emps.iterator();
while (it.hasNext()) {
Employee emp = it.next();
records.add(new String[] { emp.getId(), emp.getName(), emp.getAge(), emp.getCountry() });
}
return records;
}
}
Notice the use of custom delimiter when writing theCSV data. We have also specified the quotes character to use with fields in CSV columns. Above CSVWriter example produces following output.
[{1::Pankaj Kumar::20::India}, {2::David Dan::40::USA}, {3::Lisa Ray::28::Germany}]
'ID"https://www.journaldev.com/12014/#"Name"https://www.journaldev.com/12014/#"Age"https://www.journaldev.com/12014/#"Country'
'1"https://www.journaldev.com/12014/#"Pankaj Kumar"https://www.journaldev.com/12014/#"20"https://www.journaldev.com/12014/#"India'
'2"https://www.journaldev.com/12014/#"David Dan"https://www.journaldev.com/12014/#"40"https://www.journaldev.com/12014/#"USA'
'3"https://www.journaldev.com/12014/#"Lisa Ray"https://www.journaldev.com/12014/#"28"https://www.journaldev.com/12014/#"Germany'
OpenCSV CSVWriter ResultSet
Sometimes we want to dump our database tables data to CSV files as backup. We can do that easily using CSVWriter writeAll(ResultSet rs, boolean includeColumnNames)
method.
OpenCSV Annotation
OpenCSV provides annotation based support too. Some of the OpenCSV annotations are;
CsvBindByName
: for binding between a column name of the CSV input and a field in a bean.CsvBindByPosition
: for binding between a column number of the CSV input and a field in a bean.CsvDate
: for time based conversion.
However I don’t want to use OpenCSV annotations because then my code will become tightly coupled with OpenCSV.
That’s all for OpenCSV example tutorial.
Reference: OpenCSV Official Page