Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
334 views
in Technique[技术] by (71.8m points)

java - How to easily process CSV file to List<MyClass>

In my application I use a lot of CSV files which I have to read and build a lists based on them. I'd like to discover an easy way to do this. Do you know any easy framework which does it without using number of config files etc?

For instance, I have got a class Person:

public class Person {
    String name;
    String surname;

    double shoeSize;
    boolean sex; // true: male, false:female

    public Person() {
    }

    public String getName() {
            return name;
    }

    public void setName(String name) {
            this.name = name;
    }

    public String getSurname() {
            return surname;
    }

    public void setSurname(String surname) {
            this.surname = surname;
    }

    public double getShoeSize() {
            return shoeSize;
    }

    public void setShoeSize(double shoeSize) {
            this.shoeSize = shoeSize;
    }

    public boolean isSe) {
            return sex;
    }

    public void setSeboolean sex) {
            this.sex = sex;
    }

}

For this class, I have prepared CSV file:

name,surname,shoesize,sex
Tom,Tommy,32,true
Anna,Anny,27,false

How can I do it easily?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

One of the simplest ways to read and serialize data is by using the Jackson library. It also has an extension for CSV, you can find the wiki here

Let's say you have a Pojo like this:

@JsonPropertyOrder({ "name", "surname", "shoesize", "gender" })
public class Person {

    public String name;
    public String surname;
    public int shoesize;
    public String gender;

}

And a CSV like this:

Tom,Tommy,32,m
Anna,Anny,27,f

Then reading it is done like so:

MappingIterator<Person> personIter = new CsvMapper().readerWithTypedSchemaFor(Person.class).readValues(csvFile);
List<Person> people = personIter.readAll();

This is simple enough for my taste, basically all you need to do is add the column order in your CSV file using the @JsonPropertyOrder annotation and then just read the file using the above 2 lines.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...