JAVA中的Opencsv解析器,无法解析数据中的双引号 [英] Opencsv parser in JAVA, unable to parse double quotes in the data
本文介绍了JAVA中的Opencsv解析器,无法解析数据中的双引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下csv文件
"id","Description","vale"
1,New"Account","val1"
我无法使用opencsv jar读取上述csv文件.它不能读取New"Account
,因为数据内部用双引号引起来.我的csv阅读器构造函数如下,
I am unable to read the above csv file with opencsv jar. It cannot read New"Account
, since the double quotes inside data. My csv reader constructor is following,
csvReader = new CSVReader(new FileReader(currentFile), ',', '\"', '\0');
推荐答案
这是按设计的.您的构造函数将引号字符指定为<c1>,因此OpenCSV
会将其视为引号字符,即,当读取引号时,它将忽略所有逗号,直到找到匹配的引号为止.
That is as designed. Your constructor specifies a quote character as "\""
so OpenCSV
will treat that character as a quote character, i.e. when it reads a quote it will ignore all commas until a matching quote is found.
要解决此问题,您可以使用FilterReader
.
To get around this you could use a FilterReader
.
Reader reader = new FilterReader(fileReader) {
private int filter(int ch) {
return ch == '"'?' ':ch;
}
@Override
public int read(char[] cbuf, int off, int len) throws IOException {
int red = super.read(cbuf, off, len);
for ( int i = off; i < off + red; i++) {
cbuf[i] = (char)filter(cbuf[i]);
}
return red;
}
@Override
public int read() throws IOException {
return filter(super.read());
}
};
这篇关于JAVA中的Opencsv解析器,无法解析数据中的双引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文