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

2023年 8月 28日 84.2k 0

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

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

com.opencsv
opencsv
4.1

登录后复制

  • 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 EmployeeList = newArrayList();
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 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文件的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论