OpenCsv 读取带有转义分隔符的文件

OpenCsv reading file with escaped separator

我正在使用 opencsv 2.3,它似乎没有像我预期的那样处理转义字符。我需要能够处理不使用引号字符的 CSV 文件中的转义分隔符。

示例测试代码:

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 更改为

first field,"second\,field"

然后我得到我想要的输出:

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

但是,就我而言,我没有修改源 CSV 的选项。

不幸的是,opencsv 似乎不支持分隔符的转义,除非它们在引号中。遇到转义字符时调用以下方法(取自 opencsv 的源代码)。

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);
}

如您所见,仅当转义字符后面的字符是引号或其他转义字符时,此方法才 returns 为真。您可以将库修补到此,但以其当前形式,它不会让您做您想做的事。