• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

CsvToBean and BeanToCsv Example – Using OpenCSV

January 25, 2016 by javainterviewpoint 3 Comments

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"

Other interesting articles which you may like …

  • How to Read Excel File in Java using POI
  • How to Write Excel File in Java using POI
  • JAXB Tutorial – What is JAXB
  • JAXB Marshalling Example – Convert Java Object to XML in Java
  • JAXB UnMarshalling Example – Convert XML to Java Object
  • How to Convert Java Object to JSON using JAXB

Filed Under: Core Java, Java Tagged With: BeanToCsv Example, CSV, CsvToBean, OpenCSV, Reading, Using OpenCSV, Writing

Comments

  1. lifeinplus says

    February 11, 2016 at 9:38 pm

    Thank you for your example!
    How to get the result in a CSV File “Employee.csv” without column names?

    Reply
    • javainterviewpoint says

      February 12, 2016 at 11:20 am

      While reading

      csvReader = new CSVReader(new FileReader(“Employee.csv”),’,’,'”‘,1)

      , the last parameter corresponds to the row in the sheet which you are reading change it accordingly.

      Reply
      • lifeinplus says

        February 12, 2016 at 3:11 pm

        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.

        Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·