How to read a string containing a '\' using opencsv?

More cleaner and recommended solution is to use RFC4180Parser instead of default CSVParser:

String csv = "come,csv,string";
RFC4180Parser rfc4180Parser = new RFC4180ParserBuilder().build();
CSVReader csvReader = new CSVReaderBuilder(new StringReader(csv)).withCSVParser(rfc4180Parser).build(); 

Reference: https://sourceforge.net/p/opencsv/support-requests/50/


Maybe change the escape character in the constructor of the Reader?

CSVReader(new InputStreamReader(new FileInputStream(inFile)), ',', '"', '|') 

This is assuming | is not used in your CSV file


The backslash is for escaping the " because some values may contain a " character, and without the backslash you would not be able to have the character included.

So if you want to use \ you need to escape it with \ too, just like you would do to have it in a regular Java String.

"A",       "B",         "C",       "D"
"value 1", "value 2",   "value 3", "value 4"
"value 5", "value 6\\", "value 7", "value 8"

Either you modify your CSV file or you use another constructor from CSVReader from which you can choose the escape character

Tags:

Java

Opencsv