In my previous article we have learnt how to read/write a csv file using OpenCSV, in both Reading a CSV file and Exporting data to CSV File we just displayed the output in the console. In case of saving/retrieving the data that method will not be helpful and we will be needing the support of Object Oriented Concept (A bean for holding the values). In this example we will learn how to parse a csv file and save data to a bean and vice-versa(bean to csv file).
If you want that do it the traditional way then we have Parse the file, loop it, assign to a POJO finally add to a List like below.
List empList = new ArrayList(); String line = ""; //Read to skip the header br.readLine(); //Reading from the second line while ((line = br.readLine()) != null) { String[] employeeDetails = line.split(COMMA_DELIMITER); if(employeeDetails.length > 0 ) { //Save the employee details in Employee object Employee emp = new Employee(Integer.parseInt(employeeDetails[0]), employeeDetails[1],employeeDetails[2], Integer.parseInt(employeeDetails[3])); empList.add(emp); } }
Where as using OpenCSV we need to map the fields of POJO to CSV using ColumnPositionMappingStrategy and use the class CsvToBean to read from csv and put it to Bean and BeanToCsv for the vice-versa.
Reading a CSV Example (CsvToBean)
We will be performing the below operations for reading a csv
- Create CsvReader instance for reading the CSV file
- Using ColumnPositionMappingStrategy map the columns of POJO ( using setColumnMapping() method)
- Create object for CsvToBean class and call the parse() method passing mappingStrategy and csvReader as the parameters
- The parse() method returns List of Employees.
package com.javainterviewpoint; import java.io.FileReader; import java.util.List; import com.opencsv.CSVReader; import com.opencsv.bean.ColumnPositionMappingStrategy; import com.opencsv.bean.CsvToBean; public class ParseCSVtoJavaBean { public static void main(String args[]) { CSVReader csvReader = null; try { /** * Reading the CSV File * Delimiter is comma * Default Quote character is double quote * Start reading from line 1 */ csvReader = new CSVReader(new FileReader("Employee.csv"),',','"',1); //mapping of columns with their positions ColumnPositionMappingStrategy mappingStrategy = new ColumnPositionMappingStrategy(); //Set mappingStrategy type to Employee Type mappingStrategy.setType(Employee.class); //Fields in Employee Bean String[] columns = new String[]{"empId","firstName","lastName","salary"}; //Setting the colums for mappingStrategy mappingStrategy.setColumnMapping(columns); //create instance for CsvToBean class CsvToBean ctb = new CsvToBean(); //parsing csvReader(Employee.csv) with mappingStrategy List empList = ctb.parse(mappingStrategy,csvReader); //Print the Employee Details for(Employee emp : empList) { System.out.println(emp.getEmpId()+" "+emp.getFirstName()+" " +emp.getLastName()+" "+emp.getSalary()); } } catch(Exception ee) { ee.printStackTrace(); } finally { try { //closing the reader csvReader.close(); } catch(Exception ee) { ee.printStackTrace(); } } } }
Output :
1 FirstName1 LastName1 10000 2 FirstName2 LastName2 20000 3 FirstName3 LastName3 30000 4 FirstName4 LastName4 40000 5 FirstName5 LastName5 50000
Writing to a CSV Example (BeanToCsv)
Below operations will be performed for writing data to a CSV file
- Create CsvWriter instance for writing data to the CSV file
- Create a List of Employees which has to be written to the CSV file
- Using ColumnPositionMappingStrategy map the columns of POJO ( using setColumnMapping() method)
- Create object for BeanToCsv class and call the parse() method passing mappingStrategy, csvReader and empList as the parameters
- Employee.csv file will be created in the specified location
package com.javainterviewpoint; import java.io.FileWriter; import java.util.ArrayList; import java.util.List; import com.opencsv.CSVWriter; import com.opencsv.bean.BeanToCsv; import com.opencsv.bean.ColumnPositionMappingStrategy; public class JavaBeanToCsv { public static void main(String args[]) { CSVWriter csvWriter = null; try { //Create CSVWriter for writing to Employee.csv csvWriter = new CSVWriter(new FileWriter("Employee.csv")); BeanToCsv bc = new BeanToCsv(); //Creating Employee objects Employee emp1 = new Employee(1,"FirstName1","LastName1",10000); Employee emp2 = new Employee(2,"FirstName2","LastName2",20000); Employee emp3 = new Employee(3,"FirstName3","LastName3",30000); Employee emp4 = new Employee(4,"FirstName4","LastName4",40000); Employee emp5 = new Employee(5,"FirstName5","LastName5",50000); //Add Employee objects to a list List empList = new ArrayList(); empList.add(emp1); empList.add(emp2); empList.add(emp3); empList.add(emp4); empList.add(emp5); //mapping of columns with their positions ColumnPositionMappingStrategy mappingStrategy = new ColumnPositionMappingStrategy(); //Set mappingStrategy type to Employee Type mappingStrategy.setType(Employee.class); //Fields in Employee Bean String[] columns = new String[]{"empId","firstName","lastName","salary"}; //Setting the colums for mappingStrategy mappingStrategy.setColumnMapping(columns); //Writing empList to csv file bc.write(mappingStrategy,csvWriter,empList); System.out.println("CSV File written successfully!!!"); } catch(Exception ee) { ee.printStackTrace(); } finally { try { //closing the writer csvWriter.close(); } catch(Exception ee) { ee.printStackTrace(); } } } }
Output :
You will have a CSV File “Employee.csv” created with the below content
"empId","firstName","lastName","salary" "1","FirstName1","LastName1","10000" "2","FirstName2","LastName2","20000" "3","FirstName3","LastName3","30000" "4","FirstName4","LastName4","40000" "5","FirstName5","LastName5","50000"
lifeinplus says
Thank you for your example!
How to get the result in a CSV File “Employee.csv” without column names?
javainterviewpoint says
While reading
, the last parameter corresponds to the row in the sheet which you are reading change it accordingly.
lifeinplus says
Thanks for the answer!
It looks like I asked the question incorrectly.
File from which data is read, it does not name columns. Therefore, your option will skip the first line with important data.
Data from the fileA:
000000011, EKH3-5IDH-DNUK
000000002, P985-U0EX-02QH
When I write data to the fileB by using CSVWriter, there is a string with the name columns.
The result in the fileB:
key, value
000000011, EKH3-5IDH-DNUK
000000002, P985-U0EX-02KN
I read the data from the fileA by CsvToBean, write data to the fileB using the BeanToCsv.