Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to escape comma in CSV file

Tags:

java

csv

I have string which contains "," and need to serialize/deserialize it as CSV. i've been able to serialize it correctly, but when deserialize, it always wrong. here is my code in java

List<String> header = ...
test1,
test2, test3  <-- string contains comma ,
test4

List<String> updatedHeaderList = Lists.transform(headerList, new Function<String, String> () {
            public String apply(String input) {
                return  StringEscapeUtils.escapeCsv(input);
            }
        });

Joiner joiner = Joiner.on(separator);
        stringBuilder = joiner.appendTo(stringBuilder, updatedHeaderList);
        stringBuilder.append("\n");
        return stringBuilder.toString();

as i checked the serialized string it is: test1, "test2\, test3", test4 which looks right to me

then i tried to deserialize it:

Splitter.on(",").splitToList(resultString) 
it returned list as 
test1, 
test2,
test3,
test4

how can i deserialized it back to

test1
test2, test3
test4 

thanks

like image 293
user468587 Avatar asked Jan 29 '16 19:01

user468587


1 Answers

As per RFC 4180:

Fields containing line breaks (CRLF), double quotes, and commas should be enclosed in double-quotes.

So, the valid csv content has to be:

test1
"test2, test3"
test4 
like image 75
Dragan Bozanovic Avatar answered Oct 15 '22 19:10

Dragan Bozanovic