java – 读取分号分隔的csv
发布时间:2020-12-15 04:40:50 所属栏目:Java 来源:网络整理
导读:我有下面的代码块,它使用OpenCSV读取CSV文件并存储第7列.我面临的问题是我使用;作为CSV文件中的分隔符,但它也作为分隔符.我怎么能避免这个? 由于我们从客户端获取了不可编辑的文件,因此无法将“”置于CSV中. CSVReader reader = null; String[] nextCsvLine
我有下面的代码块,它使用OpenCSV读取CSV文件并存储第7列.我面临的问题是我使用;作为CSV文件中的分隔符,但它也作为分隔符.我怎么能避免这个?
由于我们从客户端获取了不可编辑的文件,因此无法将“”置于CSV中. CSVReader reader = null; String[] nextCsvLine = new String[50]; String splitBy = ";"; int count = 0; try { StringReader sr = new StringReader(new String(in,offset,len)); reader = new CSVReader(sr); while ((nextCsvLine = reader.readNext()) != null) { for (String linewithsemicolon : nextCsvLine) { log.debug("Line read : "+linewithsemicolon); String[] b = linewithsemicolon.split(splitBy); if (count==0){ count++; continue; } else { detailItems.add(b[7]); log.debug("7th position: "+b[7]); count++; } } 解决方法
使用带有分隔符
OpenCSV的重载版本
CSVReader(reader,';') 更新(感谢@Matt) – 更好地使用: CSVReaderBuilder(reader) .withCSVParser(CSVParserBuilder() .withSeparator(';') .build()) 我认为计数有点错误: try (CSVReader reader = new CSVReader(sr,';')) { String[] nextCsvLine; while ((nextCsvLine = reader.readNext()) != null) { int count = 0; for (String field: nextCsvLine) { log.debug("Line read : "+linewithsemicolon); if (count == 6) { // 7th column detailItems.add(field); log.debug("7th position: " + field); } count++; } } 相反,你可以做的for循环: if (nextCsvLine.length > 6) { detailItems.add(nextCsvLine[6]); } 第七个字段应该有索引6. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- Java语言描述存储结构与邻接矩阵代码示例
- java.lang.NoSuchMethodError 介绍
- java – MessageDigest.getInstance(算法)总是抛出NoSuchAl
- LC 200 Number of Islands
- java.lang.NoClassDefFoundError:org / apache / http / c
- java – 最好的弹簧验证码?
- jsp 开发之struts2中s:select标签的使用
- 读取文件 – java.io.FileNotFoundException
- 笔试编程(一) | 二分查找、数组相关
- java – Clojure:协议中没有方法的实现