Java Escaping String for Storage in csv file
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
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>