OpenCsv读取文件,带有转义的分隔符 [英] OpenCsv reading file with escaped separator

查看:1037
本文介绍了OpenCsv读取文件,带有转义的分隔符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Am使用的是opencsv 2.3,它似乎并没有像我期望的那样处理转义字符.我需要能够处理不使用引号的CSV文件中的转义分隔符.

Am using opencsv 2.3 and it does not appear to be dealing with escape characters as I expect. I need to be able to handle an escaped separator in a CSV file that does not use quoting characters.

示例测试代码:

CSVReader reader = new CSVReader(new FileReader("D:/Temp/test.csv"), ',', '"', '\\');
String[] nextLine;
while ((nextLine = reader.readNext()) != null) {
    for (String string : nextLine) {
        System.out.println("Field [" + string + "].");
    }
}

和csv文件:

first field,second\,field

和输出:

Field [first field].
Field [second].
Field [field].

请注意,如果我将csv更改为

Note that if I change the csv to

first field,"second\,field"

然后我得到以下输出:

Field [first field].
Field [second,field].

但是,就我而言,我无法选择修改源CSV.

However, in my case I do not have the option of modifying the source CSV.

推荐答案

不幸的是,看起来opencsv不支持转义分隔符,除非它们用引号引起来.当遇到转义字符时,将调用以下方法(取自opencsv的源代码).

Unfortunately it looks like opencsv does not support escaping of separator characters unless they're in quotes. The following method (taken from opencsv's source) is called when an escape character is encountered.

protected boolean isNextCharacterEscapable(String nextLine, boolean inQuotes, int i) {
    return inQuotes  // we are in quotes, therefore there can be escaped quotes in here.
            && nextLine.length() > (i + 1)  // there is indeed another character to check.
            && (nextLine.charAt(i + 1) == quotechar || nextLine.charAt(i + 1) == this.escape);
}

如您所见,仅当转义字符后的字符是引号字符或另一个转义字符时,此方法才返回true.您可以对此库进行修补,但是以其当前形式,它不会让您执行您想做的事情.

As you can see, this method only returns true if the character following the escape character is a quote character or another escape character. You could patch the library to this, but in its current form, it won't let you do what you're trying to do.

这篇关于OpenCsv读取文件,带有转义的分隔符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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