读取分号分隔的 csv

Reading semicolon delimited 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())

我认为 counting 有点错误:

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。