Java Read and Parse Csv File Using Opencsv
OpenCSV is a lightweight coffee CSV parser. Today we will expect into OpenCSV example for CSV parsing.
OpenCSV
OpenCSV provides most of the basic features for CSV parsing. OpenCSV is more than pop 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 information 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 besides 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>iii.8</version> </dependency> Before we showtime looking at example plan, we require demo CSV information and corresponding java edible bean.
Here is our sample CSV file emps.csv
1,Pankaj Kumar,xx,India 2,David Dan,40,The states 3,Lisa Ray,28,Frg Below is our java bean class to hold CSV data.
parcel com.journaldev.csv.model; public class Employee { private String id; individual Cord proper name; private String age; private String country; public String getId() { render id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.proper name = proper name; } public String getAge() { render age; } public void setAge(String age) { this.age = age; } public String getCountry() { render country; } public void setCountry(String land) { this.state = country; } @Override public String toString() { return "{" + id + "::" + name + "::" + age + "::" + state + "}"; } } Let's wait at some mutual example of CSV parsing and CSV writing.
CSVReader
Our first CSVReader instance is to read CSV file lines one by i and and so convert to list of Employee.
parcel 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 * * @writer pankaj * */ public class OpenCSVReaderLineByLineExample { public static void master(Cord[] args) throws IOException { CSVReader reader = new CSVReader(new FileReader("emps.csv"), ','); List<Employee> emps = new ArrayList<Employee>(); // read line past line String[] record = null; while ((tape = reader.readNext()) != null) { Employee emp = new Employee(); emp.setId(record[0]); emp.setName(record[ane]); emp.setAge(record[ii]); emp.setCountry(record[3]); emps.add(emp); } Arrangement.out.println(emps); reader.close(); } } Above CSVReader example is uncomplicated to empathize. One important point is to close CSVReader to avoid memory leak. Also we can specify the delimiter character, just in example you lot are using something else.
Next CSVReader instance is to read all the data in ane shot using CSVReader readAll() method.
packet com.journaldev.csv.opencsv.parser; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import coffee.util.Iterator; import coffee.util.List; import com.journaldev.csv.model.Employee; import com.opencsv.CSVReader; /** * OpenCSV CSVReader Case, Read all at in one case * * @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[] tape = iterator.adjacent(); Employee emp = new Employee(); emp.setId(record[0]); emp.setName(record[1]); emp.setAge(tape[2]); emp.setCountry(record[3]); emps.add(emp); } Arrangement.out.println(emps); reader.close(); } } CsvToBean
We want to catechumen CSV to coffee object most of the fourth dimension. Nosotros can use CsvToBean in these cases. Below is a simple example showing how to convert our employee CSV file to list of Employee objects.
packet com.journaldev.csv.opencsv.parser; import java.io.FileReader; import java.io.IOException; import coffee.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(Cord[] 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","land"}); CsvToBean<Employee> csvToBean = new CsvToBean<Employee>(); Listing<Employee> emps = csvToBean.parse(beanStrategy, reader); Organisation.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 tin have emps1.csv as below.
ID,Proper name,age, state 1,Pankaj Kumar,20,India ii,David Dan,forty,Usa iii,Lisa Ray,28,Federal republic of germany In this example nosotros tin can apply HeaderColumnNameMappingStrategy as MappingStrategy implementation. Below is the method showing HeaderColumnNameMappingStrategy usage.
// returning list of Employee for CSVWriter instance 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.shut(); return emps; } CSVWriter
Let'south have a look at CSVWriter example to write java objects to CSV a Author. We will reuse parseCSVWithHeader() defined above.
package com.journaldev.csv.opencsv.parser; import java.io.IOException; import coffee.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(Cord[] args) throws IOException { StringWriter author = new StringWriter(); //using custom delimiter and quote character CSVWriter csvWriter = new CSVWriter(author, '#', '\''); List<Employee> emps = OpenCSVParseToBeanExample.parseCSVWithHeader(); List<String[]> data = toStringArray(emps); csvWriter.writeAll(data); csvWriter.shut(); System.out.println(writer); } private static Listing<String[]> toStringArray(List<Employee> emps) { Listing<Cord[]> records = new ArrayList<String[]>(); // adding header tape records.add together(new Cord[] { "ID", "Proper name", "Historic period", "Country" }); Iterator<Employee> it = emps.iterator(); while (it.hasNext()) { Employee emp = it.adjacent(); 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 graphic symbol to use with fields in CSV columns. Above CSVWriter example produces following output.
[{1::Pankaj Kumar::xx::Bharat}, {2::David Dan::40::The states}, {3::Lisa Ray::28::Germany}] 'ID'#'Name'#'Age'#'State' '1'#'Pankaj Kumar'#'20'#'Bharat' 'two'#'David Dan'#'40'#'USA' '3'#'Lisa Ray'#'28'#'Germany' OpenCSV CSVWriter ResultSet
Sometimes we want to dump our database tables data to CSV files as backup. We can exercise that hands 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 cavalcade proper noun 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 apply OpenCSV annotations considering then my code will become tightly coupled with OpenCSV.
That'south all for OpenCSV case tutorial.
Reference: OpenCSV Official Folio
Source: https://www.journaldev.com/12014/opencsv-csvreader-csvwriter-example
Post a Comment for "Java Read and Parse Csv File Using Opencsv"