If want to store user created strings in a csv file. Is there a preferred library to use for Escaping the string or s开发者_开发技巧hould I write my own function?
For anyone looking for code:
add this to your pom.xml
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
Then use:
String escaped = StringEscapeUtils.escapeCsv("tHIS String 'needs escaping'");
System.out.println(escaped); //safe for csv
UPD: as of version 3.6, StringEscapeUtils
in commons-lang
deprecated, so you have to use commons-text
instead:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>1.6</version>
</dependency>
I suggest you use one of the libraries recommended by the post(s) here. While it may seem easy to write your own CSV creator/parser, you are going to run into issues where you need to handle scenarios such as user strings with commas or quotes in them, which can sometimes be quite cumbersome. I used the following libraries and they worked fine:-
- com.Ostermiller.util Java Utilities
- opencsv
I ended up using StringEscapeUtils, mostly because I already had the dependency in my project. Works like a charm! Cheers
If you are writing your own implementation , then here is RFC for you reference: https://www.rfc-editor.org/rfc/rfc4180
If your string are not too complicated you can easily develop small function rather than using some library. I have referenced above RFC and created small function for same purpose in one of my projects.
精彩评论