Java环境下使用CsvReader()读取CSV文件

🐓CSV文件是什么

CSV 代表逗号分隔值,是一种非常流行的文件类型。CSV文件用于存储由逗号分隔的信息。文件的每一行都用于表示一个数据记录。

🐓CSV文件的读取

🚩进行CSV文件的解析

  private List<CsvRow> getCsvFile(String filePath) {
        //新建一个CsvReadConfig配置对象
        CsvReadConfig csvReadConfig = new CsvReadConfig();
        //新建一个CsvReader对象
        CsvReader csvRows = new CsvReader(csvReadConfig);
        //初始化数据
        CsvData read = null;
            read = csvRows.read(new File(filePath), CharsetUtil.CHARSET_UTF_8);
        //读取数据
        List<CsvRow> rows = read.getRows();
        return rows;
    }

🚩Hutool包中的CsvReadConfig配置类(可以动态设置开始和结束)

import java.io.Serializable;

public class CsvReadConfig extends CsvConfig<CsvReadConfig> implements Serializable {
    private static final long serialVersionUID = 5396453565371560052L;
    protected long headerLineNo = -1L;
    protected boolean skipEmptyRows = true;
    protected boolean errorOnDifferentFieldCount;
    protected long beginLineNo;
    protected long endLineNo = 9223372036854775806L;
    protected boolean trimField;

    public CsvReadConfig() {
    }

    public static CsvReadConfig defaultConfig() {
        return new CsvReadConfig();
    }

    public CsvReadConfig setContainsHeader(boolean containsHeader) {
        return this.setHeaderLineNo(containsHeader ? this.beginLineNo : -1L);
    }

    public CsvReadConfig setHeaderLineNo(long headerLineNo) {
        this.headerLineNo = headerLineNo;
        return this;
    }

    public CsvReadConfig setSkipEmptyRows(boolean skipEmptyRows) {
        this.skipEmptyRows = skipEmptyRows;
        return this;
    }

    public CsvReadConfig setErrorOnDifferentFieldCount(boolean errorOnDifferentFieldCount) {
        this.errorOnDifferentFieldCount = errorOnDifferentFieldCount;
        return this;
    }

    public CsvReadConfig setBeginLineNo(long beginLineNo) {
        this.beginLineNo = beginLineNo;
        return this;
    }

    public CsvReadConfig setEndLineNo(long endLineNo) {
        this.endLineNo = endLineNo;
        return this;
    }

    public CsvReadConfig setTrimField(boolean trimField) {
        this.trimField = trimField;
        return this;
    }
}

  • 13
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

今天背单词了吗980

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值