加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读