Opencsv parser in JAVA, unable to parse double quotes in the data

萝らか妹 提交于 2020-01-06 02:53:10

问题


I have following csv file,

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

I am unable to read the above csv file with opencsv jar. It cannot read New"Account, since the double quotes inside data. My csv reader constructor is following,

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

回答1:


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

    };



回答2:


This is invalid csv:

1,New"Account","val1"

should be:

1,"New""Account","val1" -> if you want 1 New"Account val1

or

1,"New""Account""","val1" -> if you want 1 New"Account" val1

Quotes inside (quoted) fields, must be escaped with another quote.

While you could change your code to read the malformed csv correctly, the csv data should be fixed in the first place, because you might get some more erros with larger csv-files or updates of that data.

Usually, quotes are used when there is a seperator or another quote inside the field. So if you would ignore the quotes and only split on the seperator, there will be problems if there is a seperator inside a field in future updates of the data - for example:

1,"John, Doe",123


来源:https://stackoverflow.com/questions/34508448/opencsv-parser-in-java-unable-to-parse-double-quotes-in-the-data

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