View Javadoc

1   package org.paneris.util;
2   
3   import java.util.Enumeration;
4   import java.util.NoSuchElementException;
5   
6   /**
7    * A utility for tokenising a string made up of comma-separated
8    * variables.  Unlike Tim's effort, it handles quoted variables as
9    * well.  FIXME just don't try and read off the end if the last field
10   * is zero-length.
11   *
12   * <PRE>
13   *   foo, bar om,,"baz, ,oof",xyz   ->
14   *     "foo", " bar om", "", "baz, , oof", "xyz"
15   * </PRE>
16   *
17   * @author  williamc@paneris.org
18   */
19  
20  public class CSVStringEnumeration implements Enumeration {
21  
22    private String line = "";
23    int p = 0;
24  
25    /**
26     * Look at a new string.
27     */
28  
29    public void reset(String line) {
30      this.line = line;
31      p = 0;
32    }
33  
34    /**
35     * Are there any more tokens to come?
36     */
37  
38    public boolean hasMoreElements() {
39      return p < line.length();
40    }
41  
42    /**
43     * Return the next token as an <TT>Object</TT>.
44     */
45  
46    public final Object nextElement() {
47      return nextToken();
48    }
49  
50    /**
51     * Return the next token as a <TT>String</TT>.
52     */
53  
54    public String nextToken() {
55  
56      if (p >= line.length())
57        throw new NoSuchElementException();
58  
59      if (line.charAt(p) == '"') {
60  
61        ++p;
62        int q = line.indexOf('"', p);
63  
64        if (q == -1) {
65      p = line.length();
66      throw new IllegalArgumentException("Unclosed quotes");
67        }
68  
69        String it = line.substring(p, q);
70  
71        ++q;
72        if (q < line.length()) {
73      if (line.charAt(q) != ',') {
74        p = line.length();
75        throw new IllegalArgumentException("No comma after quotes");
76      }
77      else
78        p = q + 1;
79        }
80  
81        return it;
82      }
83      else {
84        int q = line.indexOf(',', p);
85        if (q == -1) {
86      String it = line.substring(p);
87      p = line.length();
88      return it;
89        }
90        else {
91      String it = line.substring(p, q);
92      p = q + 1;
93      return it;
94        }
95      }
96    }
97  }