我正在尝试如下解析 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 字符不被视为换行符,并且只在解析时获得两条记录?
谢谢
最佳答案
我认为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 许可证)
关于java - CSVParser 将 LF 处理为 CRLF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35579847/