关于java读取CSV文件转为bean

/**
 * 解析csv文件并转成bean
 * @param file csv文件
 * @param clazz 类
 * @param <T> 泛型
 * @return 泛型bean集合
 */
public static <T> List<T> getCsvData(MultipartFile file, Class<T> clazz) {
    InputStreamReader inputStreamReader = null;
    try {
        InputStream inputStream = getInputStream(file.getInputStream());
        inputStreamReader = new InputStreamReader(inputStream, "utf-8");
    } catch (Exception e) {
        e.printStackTrace();

    }

    HeaderColumnNameMappingStrategy<T> strategy = new HeaderColumnNameMappingStrategy<>();
    strategy.setType(clazz);

    CsvToBean<T> csvToBean = new CsvToBeanBuilder<T>(inputStreamReader)
            .withSeparator(',')
            .withQuoteChar('\'')
            .withMappingStrategy(strategy).build();
    return csvToBean.parse();
}

/**
 * 读取流中前面的字符,看是否有bom,如果有bom,将bom头先读掉丢弃
 *
 * @param in
 * @return
 * @throws IOException
 */
public static InputStream getInputStream(InputStream in) throws IOException {

    PushbackInputStream testin = new PushbackInputStream(in);
    int ch = testin.read();
    if (ch != 0xEF) {
        testin.unread(ch);
    } else if ((ch = testin.read()) != 0xBB) {
        testin.unread(ch);
        testin.unread(0xef);
    } else if ((ch = testin.read()) != 0xBF) {
        throw new IOException("错误的UTF-8格式文件");
    } else {
    }
    return testin;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值