java csv文件引号处理_java – 如何以对未闭合的双引号字符强健的方式解析大型CSV文件?...

我正在尝试解析大型CSV文件(这里的大文件意味着CSV文件通常比主内存大).我逐行处理CSV作为流,这允许我处理那些大文件.

The RFC on CSV files定义了双引号字符,将所有后来的字符视为单个字符(因此转义分隔符):

Fields containing line breaks (CRLF), double quotes, and commas

should be enclosed in double-quotes. For example:

“aaa”,”b CRLF

bb”,”ccc” CRLF

zzz,yyy,xxx

我的应用程序时不时地需要处理不正确的CSV文件,其中包含未关闭的双引号字符.这导致CSV解析器尝试从这个双引号字符开始读取文件的整个部分到一个文件,由于我的文件可能很大,可能会导致内存问题.

我想要做的是通过以某种方式检测这些问题并在这些情况下中止解析来使我的解析解决方案对这种情况稳健.可能有帮助的一件事是我知道我的字段的典型长度,所以我可能能够在字段长度的上限做一些事情.

有没有人知道一种解析CSV文件的方法,这种方式对于可以包含未绑定的双引号字符的大文件是健壮的,这样它就会在可能的情况下解析文件并在没有消耗所有可用内存时中止,当一个未闭合的双引号是当下?我目前的解析解决方案使用了OpenCSV,但如果这有助于解决问题,我对切换没有任何问题.

最佳答案 在

uniVocity-parsers中使用CSV解析器.它甚至可以解析损坏的报价转义.试试这个例子:

import java.io.*;

import java.util.*;

import com.univocity.parsers.csv.*;

public class Test {

public static void main(String ... args){

CsvParserSettings settings = new CsvParserSettings();

settings.getFormat().setLineSeparator("\r\n");

settings.setParseUnescapedQuotes(true); // THIS IS IMPORTANT FOR YOU

CsvParser parser = new CsvParser(settings);

String line1 = "something,\"a quoted value \"with unescaped quotes\" can be parsed\", something\r\n";

System.out.println("Input line: " + line1);

String line2 = "\"after the newline \r\n you will find \" more stuff\r\n";

System.out.println("Input line: " + line2);

List allLines = parser.parseAll(new StringReader(line1 + line2));

int count = 0;

for(String[] line : allLines){

System.out.println("Line " + ++count);

for(String element : line){

System.out.println("\t" + element);

}

System.out.println();

}

}

}

这将产生:

Input line: something,"a quoted value "with unescaped quotes" can be parsed", something

Input line: "after the newline

you will find " more stuff

Line 1

something

a quoted value "with unescaped quotes" can be parsed

something

Line 2

after the newline

you will find " more stuff

请注意,在第2行中,您有一条带引号字符的多行记录.在这种情况下,解析器假定这是值的一部分,因为您正在解析未转义的引号并且输入已被破坏.

现在,如果您更改此行以禁止使用引号:

settings.setParseUnescapedQuotes(false);

你会得到:

Exception in thread "main" com.univocity.parsers.common.TextParsingException: com.univocity.parsers.common.TextParsingException - Unescaped quote character '"' inside quoted value of CSV field. To allow unescaped quotes, set 'parseUnescapedQuotes' to 'true' in the CSV parser settings. Cannot parse CSV input.

Internal state when error was thrown: line=0, charIndex=29, content parsed=a quoted value

披露:我是这个图书馆的作者.它是开源和免费的(Apache V2.0许可证).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值