Java 读写csv文件

本文参考 读取CSV格式文件,请参考原文

实现的方法有:

  • 把实体类写入csv文件
  • 从csv文件读入实体类

添加依赖

<properties>
    <projecglombok.version>1.18.18</projecglombok.version>
</properties>
 
 <dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-csv</artifactId>
    <version>2.8.1</version>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>${projecglombok.version}</version>
</dependency>
View Code

有实体类如下

import lombok.Data;

@Data
public class Person {

    private String name;
    private Integer age;
    private String hobby;

    public Person(String name, Integer age, String hobby) {
        super();
        this.name = name;
        this.age = age;
        this.hobby = hobby;
    }

    /**
     * 必须,否则loadObjectList()方法会报错
     */
    public Person() {
        super();
    }

}
View Code

工具类

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.databind.MappingIterator;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvSchema;

public class CSVUtils {

    private static Logger logger = LoggerFactory.getLogger(CSVUtils.class);
    private static String csvFile = "C:\\test\\PersonList.csv";

    public static void main(String[] args) {

        // 调用objectList2CSV
        Person person1 = new Person("linda", 12, "laughing");
        Person person2 = new Person("lisa", 22, "reading");
        Person person3 = new Person("sara", 32, "sleeping");
        List<Person> persons = new ArrayList<Person>();
        persons.add(person1);
        persons.add(person2);
        persons.add(person3);

        try {
            CSVUtils.objectList2CSV(persons, new File(csvFile), Person.class);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }

        // 调用loadObjectList
        List<Person> personList = new ArrayList<>();
        try {
            personList = CSVUtils.loadObjectList(Person.class, csvFile);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }

        logger.info("size {}", personList.size());

    }

    /**
     * 从csv文件读取实体类
     */
    public static <T> List<T> loadObjectList(Class<T> type, String fileName) throws IOException {
        CsvSchema bootstrapSchema = CsvSchema.emptySchema().withHeader();
        CsvMapper mapper = new CsvMapper();
        File file = new File(fileName);
        MappingIterator<T> readValues = mapper.readerFor(type).with(bootstrapSchema).readValues(file);
        return readValues.readAll();
    }

    /**
     * 把实体类写入到csv文件
     */
    public static <T> void objectList2CSV(List<T> list, File csvFile, Class<T> clazz) throws IOException {
        CsvMapper mapper = new CsvMapper();
        CsvSchema schema = mapper.schemaFor(clazz);
        ObjectWriter writer = mapper.writer(schema.withLineSeparator("\n").withHeader());
        writer.writeValue(csvFile, list);
    }

}
View Code

 

posted on 2021-01-06 16:23  dreamstar  阅读(1379)  评论(0编辑  收藏  举报