01d4e3241e6c613a341739befab130082b875fda
[Persons_Comparator.git] / src / CSVUtils.java
1 import java.util.ArrayList;
2 import java.util.List;
3
4
5 public class CSVUtils {
6
7 private static final char DEFAULT_SEPARATOR = ',';
8 private static final char DEFAULT_QUOTE = '"';
9
10 public static List<String> parseLine(String cvsLine) {
11 return parseLine(cvsLine, DEFAULT_SEPARATOR, DEFAULT_QUOTE);
12 }
13
14 public static List<String> parseLine(String cvsLine, char separators) {
15 return parseLine(cvsLine, separators, DEFAULT_QUOTE);
16 }
17
18 public static List<String> parseLine(String cvsLine, char separators, char customQuote) {
19
20 List<String> result = new ArrayList<>();
21
22 //if empty, return!
23 if (cvsLine == null && cvsLine.isEmpty()) {
24 return result;
25 }
26
27 if (customQuote == ' ') {
28 customQuote = DEFAULT_QUOTE;
29 }
30
31 if (separators == ' ') {
32 separators = DEFAULT_SEPARATOR;
33 }
34
35 StringBuffer curVal = new StringBuffer();
36 boolean inQuotes = false;
37 boolean startCollectChar = false;
38 boolean doubleQuotesInColumn = false;
39
40 char[] chars = cvsLine.toCharArray();
41
42 for (char ch : chars) {
43
44 if (inQuotes) {
45 startCollectChar = true;
46 if (ch == customQuote) {
47 inQuotes = false;
48 doubleQuotesInColumn = false;
49 } else {
50
51 //Fixed : allow "" in custom quote enclosed
52 if (ch == '\"') {
53 if (!doubleQuotesInColumn) {
54 curVal.append(ch);
55 doubleQuotesInColumn = true;
56 }
57 } else {
58 curVal.append(ch);
59 }
60
61 }
62 } else {
63 if (ch == customQuote) {
64
65 inQuotes = true;
66
67 //Fixed : allow "" in empty quote enclosed
68 if (chars[0] != '"' && customQuote == '\"') {
69 curVal.append('"');
70 }
71
72 //double quotes in column will hit this!
73 if (startCollectChar) {
74 curVal.append('"');
75 }
76
77 } else if (ch == separators) {
78
79 result.add(curVal.toString());
80
81 curVal = new StringBuffer();
82 startCollectChar = false;
83
84 } else if (ch == '\r') {
85 //ignore LF characters
86 continue;
87 } else if (ch == '\n') {
88 //the end, break!
89 break;
90 } else {
91 curVal.append(ch);
92 }
93 }
94
95 }
96
97 result.add(curVal.toString());
98
99 return result;
100 }
101
102 }