PageRenderTime 62ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/core/src/java/liquibase/csv/opencsv/CSVReader.java

https://github.com/kanayo/liquibase
Java | 245 lines | 208 code | 11 blank | 26 comment | 0 complexity | 9e36b57558e824740d0405e14fa768c6 MD5 | raw file
  1. package liquibase.csv.opencsv;
  2. /**
  3. Copyright 2005 Bytecode Pty Ltd.
  4. Licensed under the Apache License, Version 2.0 (the "License");
  5. you may not use this file except in compliance with the License.
  6. You may obtain a copy of the License at
  7. http://www.apache.org/licenses/LICENSE-2.0
  8. Unless required by applicable law or agreed to in writing, software
  9. distributed under the License is distributed on an "AS IS" BASIS,
  10. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. See the License for the specific language governing permissions and
  12. limitations under the License.
  13. */
  14. import java.io.BufferedReader;
  15. import java.io.IOException;
  16. import java.io.Reader;
  17. import java.util.ArrayList;
  18. import java.util.List;
  19. /**
  20. * A very simple CSV reader released under a commercial-friendly license.
  21. *
  22. * @author Glen Smith
  23. *
  24. */
  25. public class CSVReader {
  26. private BufferedReader br;
  27. private boolean hasNext = true;
  28. private char separator;
  29. private char quotechar;
  30. private int skipLines;
  31. private boolean linesSkiped;
  32. /** The default separator to use if none is supplied to the constructor. */
  33. public static final char DEFAULT_SEPARATOR = ',';
  34. /**
  35. * The default quote character to use if none is supplied to the
  36. * constructor.
  37. */
  38. public static final char DEFAULT_QUOTE_CHARACTER = '"';
  39. /**
  40. * The default line to start reading.
  41. */
  42. public static final int DEFAULT_SKIP_LINES = 0;
  43. /**
  44. * Constructs CSVReader using a comma for the separator.
  45. *
  46. * @param reader
  47. * the reader to an underlying CSV source.
  48. */
  49. public CSVReader(Reader reader) {
  50. this(reader, DEFAULT_SEPARATOR);
  51. }
  52. /**
  53. * Constructs CSVReader with supplied separator.
  54. *
  55. * @param reader
  56. * the reader to an underlying CSV source.
  57. * @param separator
  58. * the delimiter to use for separating entries.
  59. */
  60. public CSVReader(Reader reader, char separator) {
  61. this(reader, separator, DEFAULT_QUOTE_CHARACTER);
  62. }
  63. /**
  64. * Constructs CSVReader with supplied separator and quote char.
  65. *
  66. * @param reader
  67. * the reader to an underlying CSV source.
  68. * @param separator
  69. * the delimiter to use for separating entries
  70. * @param quotechar
  71. * the character to use for quoted elements
  72. */
  73. public CSVReader(Reader reader, char separator, char quotechar) {
  74. this(reader, separator, quotechar, DEFAULT_SKIP_LINES);
  75. }
  76. /**
  77. * Constructs CSVReader with supplied separator and quote char.
  78. *
  79. * @param reader
  80. * the reader to an underlying CSV source.
  81. * @param separator
  82. * the delimiter to use for separating entries
  83. * @param quotechar
  84. * the character to use for quoted elements
  85. * @param line
  86. * the line number to skip for start reading
  87. */
  88. public CSVReader(Reader reader, char separator, char quotechar, int line) {
  89. this.br = new BufferedReader(reader);
  90. this.separator = separator;
  91. this.quotechar = quotechar;
  92. this.skipLines = line;
  93. }
  94. /**
  95. * Reads the entire file into a List with each element being a String[] of
  96. * tokens.
  97. *
  98. * @return a List of String[], with each String[] representing a line of the
  99. * file.
  100. *
  101. * @throws IOException
  102. * if bad things happen during the read
  103. */
  104. public List readAll() throws IOException {
  105. List allElements = new ArrayList();
  106. while (hasNext) {
  107. String[] nextLineAsTokens = readNext();
  108. if (nextLineAsTokens != null)
  109. allElements.add(nextLineAsTokens);
  110. }
  111. return allElements;
  112. }
  113. /**
  114. * Reads the next line from the buffer and converts to a string array.
  115. *
  116. * @return a string array with each comma-separated element as a separate
  117. * entry.
  118. *
  119. * @throws IOException
  120. * if bad things happen during the read
  121. */
  122. public String[] readNext() throws IOException {
  123. String nextLine = getNextLine();
  124. return hasNext ? parseLine(nextLine) : null;
  125. }
  126. /**
  127. * Reads the next line from the file.
  128. *
  129. * @return the next line from the file without trailing newline
  130. * @throws IOException
  131. * if bad things happen during the read
  132. */
  133. private String getNextLine() throws IOException {
  134. if (!this.linesSkiped) {
  135. for (int i = 0; i < skipLines; i++) {
  136. br.readLine();
  137. }
  138. this.linesSkiped = true;
  139. }
  140. String nextLine = br.readLine();
  141. if (nextLine == null) {
  142. hasNext = false;
  143. }
  144. return hasNext ? nextLine : null;
  145. }
  146. /**
  147. * Parses an incoming String and returns an array of elements.
  148. *
  149. * @param nextLine
  150. * the string to parse
  151. * @return the comma-tokenized list of elements, or null if nextLine is null
  152. * @throws IOException if bad things happen during the read
  153. */
  154. private String[] parseLine(String nextLine) throws IOException {
  155. if (nextLine == null) {
  156. return null;
  157. }
  158. List tokensOnThisLine = new ArrayList();
  159. StringBuffer sb = new StringBuffer();
  160. boolean inQuotes = false;
  161. do {
  162. if (inQuotes) {
  163. // continuing a quoted section, reappend newline
  164. sb.append("\n");
  165. nextLine = getNextLine();
  166. if (nextLine == null)
  167. break;
  168. }
  169. for (int i = 0; i < nextLine.length(); i++) {
  170. char c = nextLine.charAt(i);
  171. if (c == quotechar) {
  172. // this gets complex... the quote may end a quoted block, or escape another quote.
  173. // do a 1-char lookahead:
  174. if( inQuotes // we are in quotes, therefore there can be escaped quotes in here.
  175. && nextLine.length() > (i+1) // there is indeed another character to check.
  176. && nextLine.charAt(i+1) == quotechar ){ // ..and that char. is a quote also.
  177. // we have two quote chars in a row == one quote char, so consume them both and
  178. // put one on the token. we do *not* exit the quoted text.
  179. sb.append(nextLine.charAt(i+1));
  180. i++;
  181. }else{
  182. inQuotes = !inQuotes;
  183. // the tricky case of an embedded quote in the middle: a,bc"d"ef,g
  184. if(i>2 //not on the begining of the line
  185. && nextLine.charAt(i-1) != this.separator //not at the begining of an escape sequence
  186. && nextLine.length()>(i+1) &&
  187. nextLine.charAt(i+1) != this.separator //not at the end of an escape sequence
  188. ){
  189. sb.append(c);
  190. }
  191. }
  192. } else if (c == separator && !inQuotes) {
  193. tokensOnThisLine.add(sb.toString());
  194. sb = new StringBuffer(); // start work on next token
  195. } else {
  196. sb.append(c);
  197. }
  198. }
  199. } while (inQuotes);
  200. tokensOnThisLine.add(sb.toString());
  201. return (String[]) tokensOnThisLine.toArray(new String[0]);
  202. }
  203. /**
  204. * Closes the underlying reader.
  205. *
  206. * @throws IOException if the close fails
  207. */
  208. public void close() throws IOException{
  209. br.close();
  210. }
  211. }