读取分号分隔的csv

时间:2017-10-20 09:04:34

标签: java csv opencsv

我有以下代码块,它使用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++;
                }                   
            }

1 个答案:

答案 0 :(得分:7)

将重载版本与OpenCSV

的分隔符一起使用
CSVReader(reader, ';')

更新(感谢@Matt) - 更好地使用:

CSVReaderBuilder(reader)
    .withCSVParser(CSVParserBuilder()
    .withSeparator(';')
    .build())

我认为count有点错误:

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。

相关问题