1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.supercsv.encoder;
17
18 import org.supercsv.prefs.CsvPreference;
19 import org.supercsv.util.CsvContext;
20
21
22
23
24
25
26
27 public class DefaultCsvEncoder implements CsvEncoder {
28
29
30
31
32 public DefaultCsvEncoder() {
33 }
34
35
36
37
38 public String encode(final String input, final CsvContext context, final CsvPreference preference) {
39
40 final StringBuilder currentColumn = new StringBuilder();
41 final int delimiter = preference.getDelimiterChar();
42 final char quote = (char) preference.getQuoteChar();
43 final String eolSymbols = preference.getEndOfLineSymbols();
44 final int lastCharIndex = input.length() - 1;
45
46 boolean quotesRequiredForSpecialChar = false;
47
48 boolean skipNewline = false;
49
50 for( int i = 0; i <= lastCharIndex; i++ ) {
51
52 final char c = input.charAt(i);
53
54 if( skipNewline ) {
55 skipNewline = false;
56 if( c == '\n' ) {
57 continue;
58 }
59 }
60
61 if( c == delimiter ) {
62 quotesRequiredForSpecialChar = true;
63 currentColumn.append(c);
64 } else if( c == quote ) {
65 quotesRequiredForSpecialChar = true;
66 currentColumn.append(quote);
67 currentColumn.append(quote);
68 } else if( c == '\r' ) {
69 quotesRequiredForSpecialChar = true;
70 currentColumn.append(eolSymbols);
71 context.setLineNumber(context.getLineNumber() + 1);
72 skipNewline = true;
73 } else if( c == '\n' ) {
74 quotesRequiredForSpecialChar = true;
75 currentColumn.append(eolSymbols);
76 context.setLineNumber(context.getLineNumber() + 1);
77 } else {
78 currentColumn.append(c);
79 }
80 }
81
82 final boolean quotesRequiredForMode = preference.getQuoteMode().quotesRequired(input, context, preference);
83 final boolean quotesRequiredForSurroundingSpaces = preference.isSurroundingSpacesNeedQuotes()
84 && input.length() > 0 && (input.charAt(0) == ' ' || input.charAt(input.length() - 1) == ' ');
85
86 if( quotesRequiredForSpecialChar || quotesRequiredForMode || quotesRequiredForSurroundingSpaces ) {
87 currentColumn.insert(0, quote).append(quote);
88 }
89
90 return currentColumn.toString();
91 }
92
93 }