OpenCsv reading file with escaped separator

徘徊边缘 提交于 2019-12-04 06:29:56

问题


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.

Sample test code:

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 + "].");
    }
}

and the csv file:

first field,second\,field

and the output:

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

Note that if I change the csv to

first field,"second\,field"

then I get the output I am after:

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

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


回答1:


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

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.



来源:https://stackoverflow.com/questions/32644150/opencsv-reading-file-with-escaped-separator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!