univocity-parsers可以处理未转义的引号,并且比 opencsv 快 4 倍。试试这个代码:
public static void main(String... args){
String input = "" +
"20, \"bob, XXX\", \"test\", 30\n" +
"20, \"evan\"s,YYY \", \"test\", 30\n" +
"20, \"Tom, ZZZ\", \"test\", 30 ";
CsvParserSettings settings = new CsvParserSettings();
CsvParser parser = new CsvParser(settings);
List<String[]> rows = parser.parseAll(new StringReader(input));
//printing values enclosed in [ ] to make sure you are getting the expected result
for(String[] row : rows){
for(String value : row){
System.out.print("[" + value + "],");
}
System.out.println();
}
}
这将产生:
[20],[bob, XXX],[test],[30],
[20],["evan"s],[YYY "],[test],[30],
[20],[Tom, ZZZ],[test],[30],
此外,您可以通过以下方式之一控制如何处理未转义的引号:
settings.setUnescapedQuoteHandling(UnescapedQuoteHandling.STOP_AT_DELIMITER);
settings.setUnescapedQuoteHandling(UnescapedQuoteHandling.STOP_AT_CLOSING_QUOTE);
settings.setUnescapedQuoteHandling(UnescapedQuoteHandling.RAISE_ERROR);
settings.setUnescapedQuoteHandling(UnescapedQuoteHandling.SKIP_VALUE);
读取大文件时,您可以使用 aRowProcessor
或迭代每一行,如下所示:
parser.beginParsing(new File("/path/to/your.csv"));
String[] row;
while ((row = parser.parseNext()) != null) {
// process row
}
免责声明:我是这个库的作者。它是开源和免费的(Apache 2.0 许可证)