CSVParser 将 LF 处理为 CRLF [英] CSVParser processes LF as CRLF

查看:50
本文介绍了CSVParser 将 LF 处理为 CRLF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to parse a CSV file as below

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);列表recordList = csvParser.getRecords();

现在文件得到了以 CRLF 字符结尾的正常行,但是对于几行,中间出现了额外的 LF 字符.即

Now the file got normal lines ending with CRLF characters however for few lines there is additional LF character appearing in middle. i.e.

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

因此,解析操作创建了三个记录,而实际上它们只有两个.

Due to this, the parse operation creates three records whereas actually they are only two.

有没有办法让出现在第二行中间的 LF 字符不被视为换行符,并且仅在解析时获得两条记录?

Is there a way I can get the LF character appearing in middle of second line not treated as line break and get two records only upon parsing?

谢谢

推荐答案

我认为 uniVocity-parsers 是您会发现的唯一一个可以按预期处理行尾的解析器.

I think uniVocity-parsers is the only parser you will find that will work with line endings as you expect.

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

The equivalent code using univocity-parsers will be:

    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 而不用引号括起来,因为那不是行分隔符序列.

If you define a line separator to be \r\n then this is the ONLY sequence of characters that should identify a new record (when outside quotes). All values can have either \r or \n without being enclosed in quotes because that's NOT the line separator sequence.

解析您提供的输入样本时:

When parsing the input sample you gave:

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 许可)

Disclosure: I'm the author of this library. It's open-source and free (Apache 2.0 license)

这篇关于CSVParser 将 LF 处理为 CRLF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆