首页 > Java > java教程 > 正文

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

WBOY
发布: 2023-08-21 08:33:20
转载
1301人浏览过

使用opencsv将java beans映射到csv文件

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库添加到项目中

<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.

以上就是使用OpenCSV将Java Beans映射到CSV文件的详细内容,更多请关注php中文网其它相关文章!

java速学教程(入门到精通)
java速学教程(入门到精通)

java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:tutorialspoint网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号