【问题标题】:CSVParser processes LF as CRLFCSVParser 将 LF 处理为 CRLF
【发布时间】:2016-06-05 10:13:48
【问题描述】:

我正在尝试解析如下的 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,这是一个很好的解决方案。

标签: java csv apache-commons


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-06
    • 2016-01-13
    • 2019-09-12
    • 1970-01-01
    • 1970-01-01
    • 2022-11-10
    • 2011-03-07
    • 2016-05-19
    相关资源
    最近更新 更多