用于从 CSV 文件创建对象的 Java API

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6411357/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 05:43:33  来源:igfitidea点击:

Java API to make an object from a CSV file

javacsv

提问by Simeon

I'm looking for a library that allows me to map a .csv contents to an object.

我正在寻找一个允许我将 .csv 内容映射到对象的库。

Something like:

就像是:

public class Person {

    private String name;
    private int age;

    @CsvField("name")
    public String getName() {
        return this.name;
    }

    @CsvField("age")
    public int getAge() {
        return this.age;
    }
}

and then say something like:

然后说:

final Person filledWithDataFromCsv = csvApi.load(csvFilepath, Person.class);

from the given CSV:

从给定的 CSV:

#name, age
tom, 11
jim, 32

Does anyone know of such an API, or one that does something similar. I don't want it to use annotations as a must, I just want to be able to load the file with one line of code and a predefined class.

有谁知道这样的 API,或者有类似功能的 API。我不希望它必须使用注释,我只想能够用一行代码和一个预定义的类加载文件。

采纳答案by Vineet Reynolds

JSefaallow you to annotate Java classes that can be used in a serialization and de-serialization process. The tutorialdemonstrates how this works with the CsvIOFactory class.

JSefa允许您注释可在序列化和反序列化过程中使用的 Java 类。本教程演示了它如何与 CsvIOFactory 类一起工作。

(From the tutorial) Annotating a bean is as simple as specifying the locations of the items in the list of values, and if necessary, you'll need to specify the conversion format:

(来自教程)注释 bean 就像指定值列表中项目的位置一样简单,如有必要,您需要指定转换格式:

@CsvDataType()
public class Person {
    @CsvField(pos = 1)
    String name;

    @CsvField(pos = 2, format = "dd.MM.yyyy")
    Date   birthDate;
}

回答by Thomas Jungblut

I prefer opencsv, it is ultra simple and very clean.

我更喜欢opencsv,它非常简单而且非常干净。

http://opencsv.sourceforge.net/

http://opencsv.sourceforge.net/

For example reading:

例如阅读:

CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));
String [] nextLine;
while ((nextLine = reader.readNext()) != null) {
    // nextLine[] is an array of values from the line
    System.out.println(nextLine[0] + nextLine[1] + "etc...");
}

回答by Costi Ciudatu

There are pretty good JDBC implementations for CSV. So you can make use of such a driver, configure a datasource to use it and then use JPA (or whatever) for object-relational mapping on top of that data source.

CSV 有非常好的 JDBC 实现。因此,您可以使用这样的驱动程序,配置数据源以使用它,然后使用 JPA(或其他)在该数据源之上进行对象关系映射。

回答by user3996996

SimpleFlatMappercan do that easily see Getting Started csvusing the headers of the csv or by manually specifying which columns map to what property.

SimpleFlatMapper可以使用 csv的标题或通过手动指定哪些列映射到哪些属性来轻松查看csv 入门

CsvParser
    .mapTo(MyObject.class)
    .forEach(file, System.out::println);

回答by Jeronimo Backes

You can't go wrong with uniVocity-parsers. It supports all sorts of powerful operations and it is much faster than any other CSV parser for Java.

使用uniVocity-parsers不会出错。它支持各种强大的操作,并且比任何其他用于 Java 的 CSV 解析器都要快得多。

Here's a class with some examples:

这是一个带有一些示例的类:

class TestBean {

    // if the value parsed in the quantity column is "?" or "-", it will be replaced by null.
    @NullString(nulls = { "?", "-" })
    // if a value resolves to null, it will be converted to the String "0".
    @Parsed(defaultNullRead = "0")
    private Integer quantity;   // The attribute type defines which conversion will be executed when processing the value.

    @Trim
    @LowerCase
    // the value for the comments attribute is in the column at index 4 (0 is the first column, so this means fifth column in the file)
    @Parsed(index = 4)
    private String comments;

    // you can also explicitly give the name of a column in the file.
    @Parsed(field = "amount")
    private BigDecimal amount;

    @Trim
    @LowerCase
    // values "no", "n" and "null" will be converted to false; values "yes" and "y" will be converted to true
    @BooleanString(falseStrings = { "no", "n", "null" }, trueStrings = { "yes", "y" })
    @Parsed
    private Boolean pending;
}

Here's how to get a list of TestBean

以下是获取列表的方法 TestBean

BeanListProcessor<TestBean> rowProcessor = new BeanListProcessor<TestBean>(TestBean.class);

CsvParserSettings parserSettings = new CsvParserSettings();
parserSettings.setRowProcessor(rowProcessor);
parserSettings.setHeaderExtractionEnabled(true);

CsvParser parser = new CsvParser(parserSettings);
parser.parse(getReader("/examples/bean_test.csv"));

List<TestBean> beans = rowProcessor.getBeans();

Disclosure: I am the author of this library. It's open-source and free (Apache V2.0 license).

披露:我是这个图书馆的作者。它是开源且免费的(Apache V2.0 许可)。