微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – 读取分号分隔的csv

我有下面的代码块,它使用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.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐