Replacing the escaped quote with CSV_QUOTE, and changing the non-Writer version to reuse the Writer version - See: LANG-374

git-svn-id: https://svn.apache.org/repos/asf/commons/proper/lang/trunk@597281 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Henri Yandell 2007-11-22 01:26:39 +00:00
parent 0e68fc386b
commit d2075adb52
1 changed files with 15 additions and 15 deletions

View File

@ -40,7 +40,9 @@
*/
public class StringEscapeUtils {
private static final char[] CSV_SEARCH_CHARS = new char[] {',', '"', CharUtils.CR, CharUtils.LF};
private static final char CSV_DELIMITER = ',';
private static final char CSV_QUOTE = '"';
private static final char[] CSV_SEARCH_CHARS = new char[] {CSV_DELIMITER, CSV_QUOTE, CharUtils.CR, CharUtils.LF};
/**
* <p><code>StringEscapeUtils</code> instances should NOT be constructed in
@ -718,17 +720,15 @@ public static String escapeCsv(String str) {
if (StringUtils.containsNone(str, CSV_SEARCH_CHARS)) {
return str;
}
StringBuffer buffer = new StringBuffer(str.length() + 10);
buffer.append('"');
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c == '"') {
buffer.append('"'); // escape double quote
}
buffer.append(c);
try {
StringWriter writer = new StringWriter();
escapeCsv(writer, str);
return writer.toString();
} catch (IOException ioe) {
// this should never ever happen while writing to a StringWriter
ioe.printStackTrace();
return null;
}
buffer.append('"');
return buffer.toString();
}
/**
@ -761,15 +761,15 @@ public static void escapeCsv(Writer out, String str) throws IOException {
}
return;
}
out.write('"');
out.write(CSV_QUOTE);
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c == '"') {
out.write('"'); // escape double quote
if (c == CSV_QUOTE) {
out.write(CSV_QUOTE); // escape double quote
}
out.write(c);
}
out.write('"');
out.write(CSV_QUOTE);
}
}