1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.xnap.util;
21
22 import java.util.ArrayList;
23
24 /***
25 * Provides a string tokenizer that respects quotes. If a separator is followed
26 * by a quote the next token will extent to the next quote even if there are
27 * separators in between.
28 */
29 public class QuotedStringTokenizer
30 {
31
32
33
34 String tokens[] = new String[0];
35 int curToken = 0;
36 int count;
37
38
39
40 /***
41 * Constructs a <code>QuotedStringTokenizer</code>.
42 *
43 * @see java.util.StringTokenizer
44 */
45 public QuotedStringTokenizer(String s, String separators)
46 {
47 parse(s, separators);
48 }
49
50 /***
51 * Constructs a <code>QuotedStringTokenizer</code>.
52 *
53 * @see java.util.StringTokenizer
54 */
55 public QuotedStringTokenizer(String s)
56 {
57 this(s, " ");
58 }
59
60
61
62 /***
63 * Return the remaining tokens.
64 */
65 public String allNextTokens()
66 {
67 StringBuffer sb = new StringBuffer();
68 while (hasMoreTokens()) {
69 sb.append(nextToken());
70 if (hasMoreTokens()) {
71 sb.append(" ");
72 }
73 }
74 return sb.toString();
75 }
76
77 public int countTokens()
78 {
79 return tokens.length - curToken;
80 }
81
82 public boolean hasMoreTokens()
83 {
84 return curToken < tokens.length;
85 }
86
87 public String nextToken()
88 {
89 return tokens[curToken++];
90 }
91
92 public String[] getTokens()
93 {
94 return tokens;
95 }
96
97 protected void parse(String s, String separators)
98 {
99 int i = 0;
100 boolean inQuotes = false;
101 boolean gettingToken = true;
102 StringBuffer token = new StringBuffer("");
103 ArrayList result = new ArrayList();
104
105 while(true) {
106 if(s.length() <= i) {
107 if (token.toString().length() > 0) {
108 result.add(token.toString());
109 }
110 break;
111 }
112
113 char c = s.charAt(i++);
114 if (c == '"') {
115 if (inQuotes) {
116 result.add(token.toString());
117 token.setLength(0);
118 }
119
120 inQuotes = !inQuotes;
121 gettingToken = inQuotes;
122 }
123 else if (separators.indexOf(c) != -1) {
124 if (inQuotes) {
125 token.append(c);
126 }
127 else if (gettingToken) {
128
129 if (token.length() > 0) {
130 result.add(token.toString());
131
132 token.setLength(0);
133 gettingToken = false;
134 }
135 }
136 }
137 else {
138 token.append(c);
139 gettingToken = true;
140 }
141 }
142
143 tokens = (String[])result.toArray(tokens);
144 }
145 }