0

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.

Robert Mark Bram
  • 8,104
  • 8
  • 52
  • 73

1 Answers1

5

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.

olambert
  • 1,075
  • 2
  • 7
  • 10
  • wait what? So you can only escape a separator when it's in quotes, at which point it's already escaped by the quotes? So what is the point of this functionality? – Link19 Sep 13 '19 at 16:45