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 { 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 * <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)) { if (StringUtils.containsNone(str, CSV_SEARCH_CHARS)) {
return str; return str;
} }
StringBuffer buffer = new StringBuffer(str.length() + 10); try {
buffer.append('"'); StringWriter writer = new StringWriter();
for (int i = 0; i < str.length(); i++) { escapeCsv(writer, str);
char c = str.charAt(i); return writer.toString();
if (c == '"') { } catch (IOException ioe) {
buffer.append('"'); // escape double quote // this should never ever happen while writing to a StringWriter
ioe.printStackTrace();
return null;
} }
buffer.append(c);
}
buffer.append('"');
return buffer.toString();
} }
/** /**
@ -761,15 +761,15 @@ public static void escapeCsv(Writer out, String str) throws IOException {
} }
return; return;
} }
out.write('"'); out.write(CSV_QUOTE);
for (int i = 0; i < str.length(); i++) { for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i); char c = str.charAt(i);
if (c == '"') { if (c == CSV_QUOTE) {
out.write('"'); // escape double quote out.write(CSV_QUOTE); // escape double quote
} }
out.write(c); out.write(c);
} }
out.write('"'); out.write(CSV_QUOTE);
} }
} }