我正在使用 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);
}
如您所见,仅当转义字符后面的字符是引号字符或其他转义字符时,此方法才返回 true。您可以将库修补到此,但以目前的形式,它不会让您做您想做的事情。
关于csv - OpenCsv 读取带有转义分隔符的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57927116/