CSVReader将多行视为一行

时间:2016-09-14 16:00:48

标签: java file csv lines

我正在使用au.com.bytecode.opencsv.CSVReader读取一个csv文件并逐个打印所有记录。代码表现得很奇怪。它正确打印一些初始线。但是,之后它将一组线条打印在一起作为一条线。然后它再次正确打印下一组线。我检查了CSV文件,发现文件没有问题。

     csvReader reader = new CSVReader(new FileReader(fileNameWithLocation), ',', '\"', 1);

 ColumnPositionMappingStrategy<DomainObj> mappingStrategy = 
                            new ColumnPositionMappingStrategy<DomainObj>();

         mappingStrategy.setType(DomainObj.class);      

          String[] nextLine;

            while ((nextLine = csvReader.readNext()) != null) 
            {
                    if (nextLine != null) 
                    log.debug("Next line : " + Arrays.toString(nextLine));
            }

输出类似于:

Next line : [Line1 from the csv file]
Next line : [Line2 from the csv file]
Next line : [Line3 from the csv file]
Next line : [Line4 from the csv file]
Next line : [Line5 from the csv file]
Next line : [Line6 from the csv file]
Next line : [Line7 from the csv file]
Next line : [Line8 from the csv file]
Next line : [Line9 from the csv file
             Line10 from the csv file
             Line11 from the csv file
             Line12 from the csv file
             Line13 from the csv file
             Line14 from the csv file
            ]
Next line : [Line15 from the csv file]
Next line : [Line16 from the csv file]
Next line : [Line17 from the csv file]
Next line : [Line18 from the csv file]

1 个答案:

答案 0 :(得分:0)

看起来您在使用适当的格式(行结尾,转义等)配置解析器时遇到了问题。尝试univocity-parsers,因为它可以在大多数情况下自动检测格式,也比opencsv快4倍。试试这段代码:

CsvParserSettings settings = new CsvParserSettings();
settings.detectFormatAutomatically();

CsvParser parser = new CsvParser(settings);
parser.beginParsing(fileNameWithLocation);

String nextLine[];
while ((nextLine = parser.parseNext()) != null){
    //do stuff
}

希望这有帮助。

免责声明:我是这个图书馆的作者。它是开源和免费的(Apache 2.0许可证)