开发者

Java API to make an object from a CSV file [closed]

Closed. This question is seeking recommendations for books, tools, software libraries, and more. It does not meet Stack Overflow guidelines guidelines. It is not currently accepting answers.

We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.

Closed 5 years ago.

Improve this question

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

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, Pe开发者_开发知识库rson.class);

from the given 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.


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

(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:

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

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


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

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...");
}


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.

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

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


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.


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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜