Search code examples
javacsvopencsv

OpenCSV parser unable to parse double quotes in the data


I have following CSV file,

"id","Description","vale"
1,New"Account","val1"

I am unable to read the above CSV file with OpenCSV. It cannot read New"Account, since the double quotes inside data. My CSV reader constructor is:

csvReader = new CSVReader(new FileReader(currentFile), ',', '\"', '\0');

Solution

  • That is as designed. Your constructor specifies a quote character as "\"" so OpenCSV will treat that character as a quote character, i.e. when it reads a quote it will ignore all commas until a matching quote is found.

    To get around this you could use a FilterReader.

        Reader reader = new FilterReader(fileReader) {
    
            private int filter(int ch) {
                return ch == '"'?' ':ch;
            }
            @Override
            public int read(char[] cbuf, int off, int len) throws IOException {
                int red = super.read(cbuf, off, len);
                for ( int i = off; i < off + red; i++) {
                    cbuf[i] = (char)filter(cbuf[i]);
                }
                return red;
            }
    
            @Override
            public int read() throws IOException {
                return filter(super.read());
            }
    
        };