本文共 7669 字,大约阅读时间需要 25 分钟。
supercsv
SuperCSV motivation is to be the foremost, fastest, and most programmer-friendly, free CSV package for Java. Unfortunately we don’t have in-built CSV parser in java.
SuperCSV的动力将是针对Java的最重要,最快速,最方便程序员的免费CSV软件包。 不幸的是,我们在Java中没有内置的CSV解析器。
CellProcessor
that gives a lot of features. You can specify a column value to be NotNull, Optional, Unique. SuperCSV cell processors also support Date Time conversion, Joda Time, Enum etc. Java中有许多开源CSV解析器。 但是SuperCSV解析器是我的最爱。 Super CSV解析器的
CellProcessor
功能是CellProcessor
,它具有许多功能。 您可以将列值指定为NotNull,可选,唯一。 SuperCSV单元处理器还支持日期时间转换,乔达时间,枚举等。 Today we will look into SuperCSV example to read CSV file and convert it to list of java object. We will also have a quick look of Super CSV example program to write CSV data.
今天,我们将研究SuperCSV示例,以读取CSV文件并将其转换为Java对象列表。 我们还将快速浏览一下超级CSV示例程序,以编写CSV数据。
Before we look into example, we have to create sample CSV data and corresponding java bean.
在研究示例之前,我们必须创建示例CSV数据和相应的java bean。
1,Pankaj Kumar,20,India2,David Dan,40,USA3,Lisa Ray,28,Germany
Our corresponding java bean class is Employee.java
as defined below.
我们相应的Java bean类是Employee.java
,如下所示。
package com.journaldev.csv.model;public class Employee { private String id; private String name; private String age; private String country; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } @Override public String toString() { return "{" + id + "::" + name + "::" + age + "::" + country + "}"; }}
Add below dependency in your maven project pom.xml file to get the Super CSV jar.
在您的maven项目pom.xml文件中添加以下依赖项,以获取Super CSV jar。
net.sf.supercsv super-csv 2.4.0
Here is a simple Super CSV example program using CsvBeanReader
to parse CSV data list of java object.
这是一个使用CsvBeanReader
解析Java对象的CSV数据列表的简单Super CSV示例程序。
package com.journaldev.csv.supercsv.parser;import java.io.FileReader;import java.io.IOException;import java.util.ArrayList;import java.util.List;import org.supercsv.cellprocessor.Optional;import org.supercsv.cellprocessor.constraint.NotNull;import org.supercsv.cellprocessor.constraint.UniqueHashCode;import org.supercsv.cellprocessor.ift.CellProcessor;import org.supercsv.io.CsvBeanReader;import org.supercsv.io.ICsvBeanReader;import org.supercsv.prefs.CsvPreference;import com.journaldev.csv.model.Employee;public class SuperCSVParserExample { public static void main(String[] args) throws IOException { Listemps = new ArrayList (); ICsvBeanReader beanReader = new CsvBeanReader(new FileReader("emps.csv"), CsvPreference.STANDARD_PREFERENCE); // the name mapping provide the basis for bean setters final String[] nameMapping = new String[] { "id", "name", "age", "country" }; //to read and skip header row //final String[] header = beanReader.getHeader(true); final CellProcessor[] processors = getProcessors(); Employee emp; while ((emp = beanReader.read(Employee.class, nameMapping, processors)) != null) { emps.add(emp); } System.out.println(emps); beanReader.close(); } private static CellProcessor[] getProcessors() { final CellProcessor[] processors = new CellProcessor[] { new UniqueHashCode(), // ID new NotNull(), // Name new Optional(), // Age new NotNull() // Country }; return processors; }}
The program is simple to understand, most important part is the creation of Super CSV cell processors.
该程序简单易懂,最重要的部分是创建超级CSV单元处理器。
If your CSV file contains header row, then use beanReader.getHeader(true)
to read and skip the header for processing.
如果您的CSV文件包含标题行,请使用beanReader.getHeader(true)
读取并跳过标题以进行处理。
A simple Super CSV example using CsvBeanWriter
to write CSV data. I am assuming that age and country fields are optional.
使用CsvBeanWriter
编写CSV数据的简单Super CSV示例。 我假设年龄和国家/地区字段是可选的。
package com.journaldev.csv.supercsv.parser;import java.io.IOException;import java.io.StringWriter;import java.util.ArrayList;import java.util.List;import org.supercsv.cellprocessor.Optional;import org.supercsv.cellprocessor.constraint.NotNull;import org.supercsv.cellprocessor.constraint.UniqueHashCode;import org.supercsv.cellprocessor.ift.CellProcessor;import org.supercsv.io.CsvBeanWriter;import org.supercsv.io.ICsvBeanWriter;import org.supercsv.prefs.CsvPreference;import com.journaldev.csv.model.Employee;public class SuperCSVWriterExample { public static void main(String[] args) throws IOException { Listemps = generateDemoData(); StringWriter writer = new StringWriter(); ICsvBeanWriter beanWriter = new CsvBeanWriter(writer, CsvPreference.STANDARD_PREFERENCE); final String[] header = new String[] { "id", "name", "age", "country" }; final CellProcessor[] processors = getProcessors(); // write the header beanWriter.writeHeader(header); // write the beans data for (Employee emp : emps) { beanWriter.write(emp, header, processors); } beanWriter.close(); System.out.println("CSV Data\n" + writer.toString()); } private static CellProcessor[] getProcessors() { final CellProcessor[] processors = new CellProcessor[] { new UniqueHashCode(), // ID new NotNull(), // Name new Optional(), // Age new Optional() // Country }; return processors; } private static List generateDemoData() { List emps = new ArrayList<>(); Employee emp = new Employee(); emp.setId("1"); emp.setName("Pankaj Kumar"); emp.setAge("30"); // country is optional and not set Employee emp1 = new Employee(); emp1.setId("2"); emp1.setName("David"); emp1.setCountry("USA"); // age is optional Employee emp2 = new Employee(); emp2.setId("3"); emp2.setName("Lisa"); emp2.setAge("20"); emp2.setCountry("India"); emps.add(emp); emps.add(emp1); emps.add(emp2); return emps; }}
Above program produce below CSV output.
上面的程序产生下面的CSV输出。
CSV Dataid,name,age,country1,Pankaj Kumar,30,2,David,,USA3,Lisa,20,India
If you don’t want header row, then comment the code beanWriter.writeHeader(header)
in above program.
如果您不希望标题行,请在上面的程序中注释代码beanWriter.writeHeader(header)
。
If the above program is changed to keep the id of two Employee objects same, then we will get below exception.
如果更改上述程序以使两个Employee对象的ID保持不变,那么我们将获得以下异常。
Exception in thread "main" org.supercsv.exception.SuperCsvConstraintViolationException: duplicate value '2' encountered with hashcode 50processor=org.supercsv.cellprocessor.constraint.UniqueHashCodecontext={lineNo=4, rowNo=4, columnNo=1, rowSource=[2, Lisa, 20, India]} at org.supercsv.cellprocessor.constraint.UniqueHashCode.execute(UniqueHashCode.java:78) at org.supercsv.util.Util.executeCellProcessors(Util.java:93) at org.supercsv.io.CsvBeanWriter.write(CsvBeanWriter.java:136) at com.journaldev.csv.supercsv.parser.SuperCSVWriterExample.main(SuperCSVWriterExample.java:33)
The reason is that we have defined id column to have UniqueHashCode constraint. This is a very unique and important feature, missing in all the other CSV parsers in java.
原因是我们已将id列定义为具有UniqueHashCode约束。 这是一个非常独特且重要的功能,在Java中的所有其他CSV解析器中都没有。
That’s all for a quick SuperCSV tutorial.
这就是快速SuperCSV教程的全部内容。
Reference:
参考:
翻译自:
supercsv
转载地址:http://nfqzd.baihongyu.com/