通过url读取csv文件

/**
 * 读取CSV文件
 * 
 * @param filePath:文件路径
 */
public static Map<String, List<String>> readCSVFileWithMap(URL filePath) throws Exception {
    URLConnection conn = filePath.openConnection();
    CSVReader reader = new CSVReader(new InputStreamReader(conn.getInputStream()));
    Map<String, List<String>> map = new HashMap<>();

    String[] nextLine;
    List<String> headerList = new ArrayList<>();
    /*
    * 1、 读取到了第一行(表头行)
    * 2、 拆解数组,把内容放到list中
    * 3、 把数据放到map中(key, null) tLength : 是用来记录你有多少列
    * 4、 表格体的遍历
    * 5、 两种情况
    *       5.1  表头列数大于表格体(正常读)
    *       5.2  表头列数小于表格体(出现表头漏写)
    */
    // 记录表格行数
    int startRow = 0;
    // 记录表格列数
    int tLength = 0;
    while ((nextLine = reader.readNext()) != null) {
        startRow++;

        if (startRow == 1) {
            for (int j = 0; j < nextLine.length; j++) {
                List<String> bodyList = new ArrayList<>();
                headerList.add(nextLine[j]);
                map.put(nextLine[j], bodyList);
                if (StringUtils.isNotBlank(nextLine[j])) {
                    tLength++;
                }
            }
        } else {
            /* 读取body
            *  1、 读取每一行
            *  2、 正在遍历的是哪一列
            *  3、 是不是问题列
            *  4、 不是问题列,读取前一次map内对应列的value值
            *  5、 加入当前值到value中
            *  6、 再次put到map中
            */
            for (int k = 0; k < nextLine.length; k++) {
                if (tLength > k) {
                    String key = headerList.get(k);
                    List<String> list = map.get(key);
                    list.add(nextLine[k]);
                    
                    map.put(key, list);
                } else {
                    // 有额外列数 ,请检测表头行名
                    throw new ReaderException("reader:{}", "有额外的列数,请检测表头");
                }
            }
        }
    }
    return map;

}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值