View Javadoc

    1   package sharin.csv.parser;
    2
    3   import java.io.Reader;
    4   import java.util.ArrayList;
    5   import java.util.Iterator;
    6   import java.util.List;
    7
    8   import sharin.util.IoUtils;
    9
    10  class BasicCsvIterator implements Iterator<String[]>, CsvHandler {
    11
    12      private static final int START = 0;
    13
    14      private static final int END_RECORD = 1;
    15
    16      private static final int END_DOCUMENT = 2;
    17
    18      private final Reader reader;
    19
    20      private final BasicCsvAutomaton automaton;
    21
    22      private List<String> valueList;
    23
    24      private StringBuilder valueBuilder;
    25
    26      private int state;
    27
    28      private String[] record;
    29
    30      public BasicCsvIterator(Reader reader, char separator) {
    31          this.reader = reader;
    32          this.automaton = new BasicCsvAutomaton(this, separator);
    33          state = START;
    34      }
    35
    36      public boolean hasNext() {
    37          record = nextRecord();
    38          return record != null;
    39      }
    40
    41      public String[] next() {
    42          return record;
    43      }
    44
    45      public void remove() {
    46          throw new UnsupportedOperationException();
    47      }
    48
    49      private String[] nextRecord() {
    50
    51          if (state == END_DOCUMENT) {
    52              return null;
    53          }
    54
    55          valueList = null;
    56          valueBuilder = null;
    57          state = START;
    58
    59          while (true) {
    60              automaton.put(IoUtils.read(reader));
    61
    62              if (state != START) {
    63                  break;
    64              }
    65          }
    66
    67          if (valueList == null) {
    68              return null;
    69          }
    70
    71          return valueList.toArray(new String[valueList.size()]);
    72      }
    73
    74      public void startDocument() {
    75          /* do nothing */
    76      }
    77
    78      public void startRecord() {
    79          valueList = new ArrayList<String>();
    80      }
    81
    82      public void startValue() {
    83          valueBuilder = new StringBuilder();
    84      }
    85
    86      public void character(char ch) {
    87          valueBuilder.append(ch);
    88      }
    89
    90      public void endValue() {
    91          valueList.add(valueBuilder.toString());
    92          valueBuilder = null;
    93      }
    94
    95      public void endRecord() {
    96          state = END_RECORD;
    97      }
    98
    99      public void endDocument() {
    100         state = END_DOCUMENT;
    101     }
    102 }