CSVParser将LF处理为CRLF

时间:2016-02-23 14:14:13

标签: java csv apache-commons

我正在尝试解析CSV文件,如下所示

String NEW_LINE_SEPARATOR = "\r\n"; CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator(NEW_LINE_SEPARATOR); FileReader fr = new FileReader("201404051539.csv"); CSVParser csvParser = csvFileFormat.withHeader().parse(fr); List<CSVRecord> recordsList = csvParser.getRecords();

现在文件的正常行以CRLF字符结尾,但是对于很少的行,中间会出现额外的LF字符。 即。

    a,b,c,dCRLF --line1
    e,fLF,g,h,iCRLF --line2

由于这个原因,解析操作创建了三个记录,而实际上它们只有两个。

有没有办法可以让LF字符出现在第二行中间而不被视为换行符,只有在解析时才会得到两个记录?

由于

1 个答案:

答案 0 :(得分:2)

我认为uniVocity-parsers是您能找到的唯一可以按预期使用行结尾的解析器。

使用univocity-parsers的等效代码将是:

    CsvParserSettings settings = new CsvParserSettings(); //many options here, check the tutorial
    settings.getFormat().setLineSeparator("\r\n");
    settings.getFormat().setNormalizedNewline('\u0001'); //uses a special character to represent a new record instead of \n.
    settings.setNormalizeLineEndingsWithinQuotes(false); //does not replace \r\n by the normalized new line when reading quoted values.
    settings.setHeaderExtractionEnabled(true); //extract headers from file
    settings.trimValues(false); //does not remove whitespaces around values 
    CsvParser parser = new CsvParser(settings);

    List<Record> recordsList = parser.parseAllRecords(new File("201404051539.csv"));

如果将行分隔符定义为\ r \ n,那么这是唯一应标识新记录的字符序列(当引用外部时)。所有值都可以有\ r或\ n而不用引号括起来,因为那不是行分隔符序列。

解析输入样本时,您给出了:

String input = "a,b,c,d\r\ne,f\n,g,h,i\r\n";
parser.parseAll(new StringReader(input));

结果将是:

LINE1 = [a, b, c, d]
LINE2 = [e, f
, g, h, i]

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

相关问题