使用OpenCSV将Java Beans映射到CSV文件

2024-03-04 0 3,178

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.

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

使用OpenCSV将Java Beans与CSV文件进行映射需要四个主要步骤 - 定义、创建、映射和写入。在介绍这四个步骤之前,我们先来看看使用OpenCSV将Java Beans映射到CSV的四个步骤:定义Java Bean、创建CSVWriter、将Java Bean映射到CSV以及写入CSV记录。在定义Java Bean之后,创建一个CSVWriter来处理和处理数据的写入。接下来是将您的Java Bean映射到CSV文件,提供写入器所需的信息。最后,使用CSVWriter写入记录,从而确保您的数据以您希望的方式表达出来。通过这四个步骤,您将在掌握使用OpenCSV将Java Beans映射到CSV的艺术方面迈出坚实的一步。

将OpenCSV库添加到项目中

  • 步骤 1 - 对于 Maven 项目,在 pom.xml 文件中包含 OpenCSV 的 Maven 依赖。

<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

  • 第一步 - 创建一个Writer实例,用于将数据写入CSV文件

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 −

  • 使用StatefulBeanToCSVBuilder对象的withMappingStrategy函数,将ColumnPositionMappingStrategy应用于。

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

  • 通过StatefulBeanToCSVBuilder对象的withQuotechar函数,生成的csv文件的withQuotechar。

StatefulBeanToCsv beanToCsv = new StatefulBeanToCsvBuilder(writer)
.withMappingStrategy(mappingStrategy)
. withSeparator('#')
.withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)
. build ();
  • 第5步 - 在创建后,可以通过使用StatefulBeanToCsv对象中的write方法,将对象列表或单个对象添加到csv文件中。

beanToCsv.write(Employeelist);

Example

我们的目标是创建一个包含重要属性(如姓名、年龄、公司和薪水)的员工对象的综合列表。然后,我们将生成一个名为Employees.csv的CSV文件,其中包含员工对象。

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"

结论

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.

资源下载此资源下载价格为1小猪币,终身VIP免费,请先
由于本站资源来源于互联网,以研究交流为目的,所有仅供大家参考、学习,不存在任何商业目的与商业用途,如资源存在BUG以及其他任何问题,请自行解决,本站不提供技术服务! 由于资源为虚拟可复制性,下载后不予退积分和退款,谢谢您的支持!如遇到失效或错误的下载链接请联系客服QQ:442469558

:本文采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可, 转载请附上原文出处链接。
1、本站提供的源码不保证资源的完整性以及安全性,不附带任何技术服务!
2、本站提供的模板、软件工具等其他资源,均不包含技术服务,请大家谅解!
3、本站提供的资源仅供下载者参考学习,请勿用于任何商业用途,请24小时内删除!
4、如需商用,请购买正版,由于未及时购买正版发生的侵权行为,与本站无关。
5、本站部分资源存放于百度网盘或其他网盘中,请提前注册好百度网盘账号,下载安装百度网盘客户端或其他网盘客户端进行下载;
6、本站部分资源文件是经压缩后的,请下载后安装解压软件,推荐使用WinRAR和7-Zip解压软件。
7、如果本站提供的资源侵犯到了您的权益,请邮件联系: 442469558@qq.com 进行处理!

猪小侠源码-最新源码下载平台 Java教程 使用OpenCSV将Java Beans映射到CSV文件 http://www.20zxx.cn/808705/xuexijiaocheng/javajc.html

猪小侠源码,优质资源分享网

常见问题
  • 本站所有资源版权均属于原作者所有,均只能用于参考学习,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担
查看详情
  • 最常见的情况是下载不完整: 可对比下载完压缩包的与网盘上的容量,建议提前注册好百度网盘账号,使用百度网盘客户端下载
查看详情

相关文章

官方客服团队

为您解决烦忧 - 24小时在线 专业服务