Mapping Java Beans to CSV Using OpenCSV


In our digitized era where large amounts of information are produced every day around the globe; managing information storage methods efficiently has become crucially important to many domains -including businesses- in order to be successful . One alternative that has gained great popularity among users lately due its effective functionality along with convenience aspects; economical point of view could well be considered would be Comma Separated Values (CSV) file format. It's a text-based option which could help in storing, manipulating and transmitting data in an uncomplicated and lightweight way. Nonetheless, mapping CSVs to more intricate data structures examples like Java Beans may represent a tough challenge on some instances; but with OpenCSV it is possible to make everything more understandable and enable that mapping process into Java Beans format.

What is OpenCSV?

One essential tool for managing CSV files in Java is OpenCSV. This highly-regarded library comes standard with an easily-navigable API allowing you to read/write files containing headers while utilizing custom delimiters as well as escaping characters - without breaking a sweat! Another huge benefit offered by OpenCSV involves facilitating the simplified mapping of intricately-structured data sets directly onto corresponding Bean classes. OpenCSV provides users with an effective way to create stylish and varied content - perplexity and burliness come together to create an optimal output.

Mapping Java Beans to CSV Using OpenCSV

Writing mappings between Java Beans and CSV files with OpenCSV requires four primary steps - definition, creation, mapping, and writing. Before cutting to the chase with these four steps, the four steps of mapping Java Beans to CSV using OpenCSV: define the Java Bean, create a CSVWriter, map the Java Bean to CSV, and write the CSV records. After defining your java bean, create a CSVWriter to process and handle the writing of data. Next up is mapping your java bean to the CSV file, providing the information the writer needs. Finally, write the records with the CSVWriter, thus ensuring your data is expressed how you want it to. With these four steps, you'll be well on your way to mastering the art of mapping Java Beans to CSV with OpenCSV.

Add OpenCSV library to the Project

  • Step 1 − For maven project, include the OpenCSV maven dependency in pom.xml.file.

<dependency>
   <groupId>com.opencsv</groupId>
   <artifactId>opencsv</artifactId>
   <version>4.1</version>
</dependency>
  • Step 2 − For Gradle project, include the OpenCSV dependency

Compile group: "com.opencsv", name: "opencsv", version: "4.1"
  • Step 3 − You can also download OpenCSV JAR and include it in your project class path.

Mapping Java Beans to CSV

  • Step 1 − Create a Writer instance for writing data to CSV file

Writer writer =
Files.newbufferedWriter(Paths.get(file_location));
  • Step 2 − Create a list of objects which are required to be written in the CSV file

  • Step 3 − Using ColumnPositionMappingStrategy map the columns of created objects, to column of CSV

ColumnPositionMappingStrategy mappingStrategy = new
ColumnPositionMappingStrategy();
mappingStrategy.setType(Employee.class);
//where employee is the object to be mapped with CSV
  • Step 4 − Create object of StatefulBeanToCSV class by calling build method of StatefulBeanToCSVBuilder class with writer object as a parameter. According to the needs the user might also provide −

  • ColumnPositionMappingStrategy with the help of withMappingStrategy function of StatefulBeanToCSVBuilder object.

  • Separator of generated CSV file with the help of withSeparator function of StatefulBeanToCSVBuilder object.

  • withQuotechar of generated csv file with the help of withQuotechar function of StatefulBeanToCSVBuilder object.

StatefulBeanToCsv beanToCsv = new StatefulBeanToCsvBuilder(writer)
.withMappingStrategy(mappingStrategy)
. withSeparator('#')
.withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)
. build ();
  • Step 5 − Upon creation, one may add a list of objects or singular objects to a csv file through utilization of the write method within the StatefulBeanToCsv object.

beanToCsv.write(Employeelist);

Example

Our goal is to craft a comprehensive list of Employee objects, each consisting of important attributes like Name, Age, Company and Salary. Then we will generate a CSV file Employees.csv which contains Employee object.

Employee.java

public class Employee {

   public String Name, Age, Company, Salary;

   public Employee(String name, String age,
      String company, String salary) {
      super();
      Name = name;
      Age = age;
      Company = company;
      Salary = salary;
   }
   
   @Override
   public String toString() {
      return "Employee [Name=" + Name + ",
      Age=" + Age + ", Company=" + Company + ",
      Salary=" + Salary + "]";
   }
}

BeanToCSV.java

import java.io.FileWriter;
import java.io.Writer;
import java.nio.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import com.opencsv.bean.ColumnPositionMappingStrategy;
import com.opencsv.bean.StatefulBeanToCsv;
import com.opencsv.bean.StatefulBeanToCsvBuilder;

public class BeanToCSV {
   public static void main(String[] args) {

      // name of generated csv
      final String CSV_LOCATION = "Employees.csv ";

      try {

         // Creating writer class to generate
         // csv file
         FileWriter writer = newFileWriter(CSV_LOCATION);

         // create a list of employees
         List<Employee> EmployeeList = newArrayList<Employee>();
         Employee emp1 = new Employee
            ("Anurag", "24", "HTc", "75000");
         Employee emp2 = new Employee
            ("Amaan", "24", "Microsoft", "79000");
         Employee emp3 = new Employee
            ("Rashi", "26", "TCS", "39000");
         Employee emp4 = new Employee
            ("Varun", "22", "NgGear", "15000");
         Employee emp5 = new Employee
            ("Pranjal", "29", "Sath", "51000");
         EmployeeList.add(emp1);
         EmployeeList.add(emp2);
         EmployeeList.add(emp3);
         EmployeeList.add(emp4);
         EmployeeList.add(emp5);

         // Create Mapping Strategy to arrange the
         // column name in order
         ColumnPositionMappingStrategy mappingStrategy=
            new ColumnPositionMappingStrategy();
         mappingStrategy.setType(Employee.class);

         // Arrange column name as provided in below array.
         String[] columns = new String[]
            { "Name", "Age", "Company", "Salary" };
         mappingStrategy.setColumnMapping(columns);

         // Creating StatefulBeanToCsv object
         StatefulBeanToCsvBuilder<Employee> builder=
               new StatefulBeanToCsvBuilder(writer);
         StatefulBeanToCsv beanWriter =
            builder.withMappingStrategy(mappingStrategy).build();

         // Write list to StatefulBeanToCsv object
         beanWriter.write(EmployeeList);

         // closing the writer object
         writer.close();
      }
      catch (Exception e) {
         e.printStackTrace();
      }
   }
}

Output

EmployeeData.csv
CSV file contains: ----

"Anurag", "24", "HTc", "75000"
"Amaan", "24", "Microsoft", "79000"
"Rashi", "26", "TCS", "39000"
"Varun", "22", "NgGear", "15000"
"Pranjal", "29", "Sath", "51000"

Conclusion

Java's Open CSV is a powerful tool that simplifies reading and writing of CSV files, so if you need a simpler way of dealing with complex data structures within your CSV files look no further than Open CSV - the tool which maps Java beans into the format. A simple definition of the Java Bean coupled with mapping it to CSV is enough to produce well-written CSV record through those few lines of code, and the flexibility and dependability of Open CSV make it a vital component for effectively managing CSV files in data-driven applications.

Updated on: 28-Jul-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements