CSVParser 处理 LF 时将其视为 CRLF

3
我将尝试解析以下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字符不被视为换行符并且在解析时仅获得两条记录?谢谢。

你可以先尝试将所有LF替换为无,例如:String newLine = oldLine.replace ("\n", ""); 然后继续解析。 - mnille
谢谢 @mnille,这是个好的解决方案。 - user2654241
1个回答

3

我认为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许可证)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接