简体   繁体   中英

Using Escape characters in openCSV

I am using the default constructor and the default escape character which is backslash. So the CSV format is like this "value1","value2","value3","value4"

The values are read from the CSV file , Windows XP OS.

Now the problem is that when the value as a double quote in it like this "aa"," I am "fine", what about u?", "232", I do not understand how to escape the double quote.

Can some one please help me here?

Double quote the quote characters

    CSVParser csv = new CSVParser()

    String[] result = csv.parseLine('"aa","I am ""fine"", what about u?", "232"')

    assert result[0] == 'aa'
    assert result[1] == 'I am "fine", what about u?'
    assert result[2] == '232'

Update

This answer was an extract from the following groovy test file OpenCSVTest.groovy :

import groovy.util.GroovyTestCase
import au.com.bytecode.opencsv.CSVReader
import au.com.bytecode.opencsv.CSVParser

@Grapes([
    @Grab(group='net.sf.opencsv', module='opencsv', version='2.3')
])

class OpenCSVTest extends GroovyTestCase {

    void testParseQuote() {
        CSVParser csv = new CSVParser()

        String[] result = csv.parseLine('"aa","I am ""fine"", what about u?", "232"')

        assert result[0] == 'aa'
        assert result[1] == 'I am "fine", what about u?'
        assert result[2] == '232'
    }
}

Run as follows:

$ groovy OpenCSVTest
.
Time: 0.009

OK (1 test)

In your question you tell that you are using the default escape character which is backslash. So you have to use the backslash... Like: "aa"," I am \\"fine\\", what about u?", "232"

Test it from code like this:

CSVParser csvParser = new CSVParser();
String[] parseLine = csvParser.parseLine("\"aa\",\" I am \"\"fine\"\", what about u?\", \"232\"");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM