简体   繁体   中英

CSV reader creating problem with special character (“),("),('),(/) while reading the CSV file by java code?

Sample Data:

"Here Comes Santa Claus (from “pitch Perfect 2" Soundtrack)","PITCH PERFECT 2",NULL,"Here Comes ameda Claus (from “amen Perfect 2" Amen)",NULL,"HERE COMES SANTA CLAUS (FROM “PITCH PERFECT 2" SOUNDTRACK)",NULL,"PITCH IMPACT 2","00-00-0000 00:00:00".

Use this pom.xml dependency to read file :

<dependency>
        <groupId>com.opencsv</groupId>
        <artifactId>opencsv</artifactId>
        <version>4.1</version>
</dependency>

Using the below java code :

RFC4180Parser rfc4180Parser = new RFC4180ParserBuilder().build();
CSVReaderBuilder csvReaderBuilder = new CSVReaderBuilder(filereader)
                    .withCSVParser(rfc4180Parser);
csvReader = csvReaderBuilder.build();
String[] nextRecord;
int i=0;
            while ((nextRecord = csvReader.readNext()) != null) {
    System.out.println("Data " + nextRecord [i]);
    System.out.println("New Records");

}

My output :-

Here Comes Santa Claus (from “pitch Perfect 2" Soundtrack)","PITCH PERFECT 2",NULL,"Here Comes ameda Claus (from “amen Perfect 2" Amen)",NULL,"HERE COMES SANTA CLAUS (FROM “PITCH PERFECT 2" SOUNDTRACK)
New Records
NULL
New Records
PITCH IMPACT 2
New Records
00-00-0000 00:00:00
New Records

Output should be like this :--

Comes Comes Santa Amen(from “Amen Amen2" Amen)
New Records
Amen2Amen22
New Records
NULL
New Records
Amen2 ameda Claus (from “amen Amen2 2" Amen)
New Records
NULL
New Records
HERE COMES SANTA CLAUS (FROM “PITCH PERFECT 2" SOUNDTRACK)
New Records
NULL
New Records
PITCH IMPACT 2
New Records
00-00-0000 00:00:00
New Records

As @Janoz says, your CSV isn't valid, because you have quotes ( " ) inside the values that need to be escaped.

Since you are using a RFC 4180 parser you need to escape them by duplicating the quotes:

"Here Comes Santa Claus (from “pitch Perfect 2"" Soundtrack)","PITCH PERFECT 2",NULL,"Here Comes ameda Claus (from “amen Perfect 2"" Amen)",NULL,"HERE COMES SANTA CLAUS (FROM “PITCH PERFECT 2"" SOUNDTRACK)",NULL,"PITCH IMPACT 2","00-00-0000 00:00:00".

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