前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >javacsv 根据列名获取不到第一列问题

javacsv 根据列名获取不到第一列问题

作者头像
明明如月学长
发布2021-08-27 16:22:50
1K0
发布2021-08-27 16:22:50
举报
文章被收录于专栏:明明如月的技术专栏

使用javacsv来操作csv文件,此文件为UTF-8格式。

发现有一列通过get(String columnName)方式获取不到,其他列都可以,而且名称反复核对都OK。

单步跟踪发现问题,跟到java8的 HashMap里

到了

代码语言:javascript
复制
/**
 * Returns the value to which the specified key is mapped,
 * or {@code null} if this map contains no mapping for the key.
 *
 * More formally, if this map contains a mapping from a key
 * {@code k} to a value {@code v} such that {@code (key==null ? k==null :
 * key.equals(k))}, then this method returns {@code v}; otherwise
 * it returns {@code null}.  (There can be at most one such mapping.)
 *
 * A return value of {@code null} does not necessarily
 * indicate that the map contains no mapping for the key; it's also
 * possible that the map explicitly maps the key to {@code null}.
 * The {@link #containsKey containsKey} operation may be used to
 * distinguish these two cases.
 *
 * @see #put(Object, Object)
 */
public V get(Object key) {
    Node<K,V> e;
    return (e = getNode(hash(key), key)) == null ? null : e.value;
}

此时key为带获取的csv头的列名supplierId,然后跟进去

代码语言:javascript
复制
/**
 * Implements Map.get and related methods
 *
 * @param hash hash for key
 * @param key the key
 * @return the node, or null if none
 */
final Node<K,V> getNode(int hash, Object key) {
    Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
    if ((tab = table) != null && (n = tab.length) > 0 &&
        (first = tab[(n - 1) & hash]) != null) {
        if (first.hash == hash && // always check first node
            ((k = first.key) == key || (key != null && key.equals(k))))
            return first;
        if ((e = first.next) != null) {
            if (first instanceof TreeNode)
                return ((TreeNode<K,V>)first).getTreeNode(hash, key);
            do {
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    return e;
            } while ((e = e.next) != null);
        }
    }
    return null;
}

调试页面显示:

此时传入的hash值和key对应的hash值并不对应。

反复调试发现问题

supplierId前面明明没有字符怎么多了个\uFEFF?

查阅资料发现 “Windows平台下Unicode文件(UTF-8等)头部插入BOM首字符”,supplierId确实是头部第一列的列名,因此可以确定这个是BOM首字符。

因此将文件保存为UTF-8( without BOM)重新读取就可以了,使用sublime text再File-Save with Encoding中选择UTF-8即可却去掉BOM头。

或者读取第一个字符时应该判断是否以上述unicode字符开头,跳过即可。

可以继承CsvReader重写 其中的readRecord函数 在while循环里,当columsCount =0时,跳过此BOM头。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018/06/09 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
文件存储
文件存储(Cloud File Storage,CFS)为您提供安全可靠、可扩展的共享文件存储服务。文件存储可与腾讯云服务器、容器服务、批量计算等服务搭配使用,为多个计算节点提供容量和性能可弹性扩展的高性能共享存储。腾讯云文件存储的管理界面简单、易使用,可实现对现有应用的无缝集成;按实际用量付费,为您节约成本,简化 IT 运维工作。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档