author | alanb |
Sat, 27 Jun 2009 21:46:53 +0100 | |
changeset 3065 | 452aaa2899fc |
parent 2057 | 3acf8e5e2ca0 |
child 3631 | 4dc04372d56b |
permissions | -rw-r--r-- |
2 | 1 |
/* |
2057
3acf8e5e2ca0
6781363: New I/O: Update socket-channel API to jsr203/nio2-b99
alanb
parents:
2
diff
changeset
|
2 |
* Copyright 2003-2009 Sun Microsystems, Inc. All Rights Reserved. |
2 | 3 |
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. |
4 |
* |
|
5 |
* This code is free software; you can redistribute it and/or modify it |
|
6 |
* under the terms of the GNU General Public License version 2 only, as |
|
7 |
* published by the Free Software Foundation. Sun designates this |
|
8 |
* particular file as subject to the "Classpath" exception as provided |
|
9 |
* by Sun in the LICENSE file that accompanied this code. |
|
10 |
* |
|
11 |
* This code is distributed in the hope that it will be useful, but WITHOUT |
|
12 |
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or |
|
13 |
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License |
|
14 |
* version 2 for more details (a copy is included in the LICENSE file that |
|
15 |
* accompanied this code). |
|
16 |
* |
|
17 |
* You should have received a copy of the GNU General Public License version |
|
18 |
* 2 along with this work; if not, write to the Free Software Foundation, |
|
19 |
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. |
|
20 |
* |
|
21 |
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, |
|
22 |
* CA 95054 USA or visit www.sun.com if you need additional information or |
|
23 |
* have any questions. |
|
24 |
*/ |
|
25 |
||
26 |
package java.util; |
|
27 |
||
2057
3acf8e5e2ca0
6781363: New I/O: Update socket-channel API to jsr203/nio2-b99
alanb
parents:
2
diff
changeset
|
28 |
import java.nio.file.FileRef; |
2 | 29 |
import java.util.regex.*; |
30 |
import java.io.*; |
|
31 |
import java.math.*; |
|
32 |
import java.nio.*; |
|
33 |
import java.nio.channels.*; |
|
34 |
import java.nio.charset.*; |
|
35 |
import java.text.*; |
|
36 |
import java.util.Locale; |
|
37 |
import sun.misc.LRUCache; |
|
38 |
||
39 |
/** |
|
40 |
* A simple text scanner which can parse primitive types and strings using |
|
41 |
* regular expressions. |
|
42 |
* |
|
43 |
* <p>A <code>Scanner</code> breaks its input into tokens using a |
|
44 |
* delimiter pattern, which by default matches whitespace. The resulting |
|
45 |
* tokens may then be converted into values of different types using the |
|
46 |
* various <tt>next</tt> methods. |
|
47 |
* |
|
48 |
* <p>For example, this code allows a user to read a number from |
|
49 |
* <tt>System.in</tt>: |
|
50 |
* <blockquote><pre> |
|
51 |
* Scanner sc = new Scanner(System.in); |
|
52 |
* int i = sc.nextInt(); |
|
53 |
* </pre></blockquote> |
|
54 |
* |
|
55 |
* <p>As another example, this code allows <code>long</code> types to be |
|
56 |
* assigned from entries in a file <code>myNumbers</code>: |
|
57 |
* <blockquote><pre> |
|
58 |
* Scanner sc = new Scanner(new File("myNumbers")); |
|
59 |
* while (sc.hasNextLong()) { |
|
60 |
* long aLong = sc.nextLong(); |
|
61 |
* }</pre></blockquote> |
|
62 |
* |
|
63 |
* <p>The scanner can also use delimiters other than whitespace. This |
|
64 |
* example reads several items in from a string: |
|
65 |
*<blockquote><pre> |
|
66 |
* String input = "1 fish 2 fish red fish blue fish"; |
|
67 |
* Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*"); |
|
68 |
* System.out.println(s.nextInt()); |
|
69 |
* System.out.println(s.nextInt()); |
|
70 |
* System.out.println(s.next()); |
|
71 |
* System.out.println(s.next()); |
|
72 |
* s.close(); </pre></blockquote> |
|
73 |
* <p> |
|
74 |
* prints the following output: |
|
75 |
* <blockquote><pre> |
|
76 |
* 1 |
|
77 |
* 2 |
|
78 |
* red |
|
79 |
* blue </pre></blockquote> |
|
80 |
* |
|
81 |
* <p>The same output can be generated with this code, which uses a regular |
|
82 |
* expression to parse all four tokens at once: |
|
83 |
*<blockquote><pre> |
|
84 |
* String input = "1 fish 2 fish red fish blue fish"; |
|
85 |
* Scanner s = new Scanner(input); |
|
86 |
* s.findInLine("(\\d+) fish (\\d+) fish (\\w+) fish (\\w+)"); |
|
87 |
* MatchResult result = s.match(); |
|
88 |
* for (int i=1; i<=result.groupCount(); i++) |
|
89 |
* System.out.println(result.group(i)); |
|
90 |
* s.close(); </pre></blockquote> |
|
91 |
* |
|
92 |
* <p>The <a name="default-delimiter">default whitespace delimiter</a> used |
|
93 |
* by a scanner is as recognized by {@link java.lang.Character}.{@link |
|
94 |
* java.lang.Character#isWhitespace(char) isWhitespace}. The {@link #reset} |
|
95 |
* method will reset the value of the scanner's delimiter to the default |
|
96 |
* whitespace delimiter regardless of whether it was previously changed. |
|
97 |
* |
|
98 |
* <p>A scanning operation may block waiting for input. |
|
99 |
* |
|
100 |
* <p>The {@link #next} and {@link #hasNext} methods and their |
|
101 |
* primitive-type companion methods (such as {@link #nextInt} and |
|
102 |
* {@link #hasNextInt}) first skip any input that matches the delimiter |
|
103 |
* pattern, and then attempt to return the next token. Both <tt>hasNext</tt> |
|
104 |
* and <tt>next</tt> methods may block waiting for further input. Whether a |
|
105 |
* <tt>hasNext</tt> method blocks has no connection to whether or not its |
|
106 |
* associated <tt>next</tt> method will block. |
|
107 |
* |
|
108 |
* <p> The {@link #findInLine}, {@link #findWithinHorizon}, and {@link #skip} |
|
109 |
* methods operate independently of the delimiter pattern. These methods will |
|
110 |
* attempt to match the specified pattern with no regard to delimiters in the |
|
111 |
* input and thus can be used in special circumstances where delimiters are |
|
112 |
* not relevant. These methods may block waiting for more input. |
|
113 |
* |
|
114 |
* <p>When a scanner throws an {@link InputMismatchException}, the scanner |
|
115 |
* will not pass the token that caused the exception, so that it may be |
|
116 |
* retrieved or skipped via some other method. |
|
117 |
* |
|
118 |
* <p>Depending upon the type of delimiting pattern, empty tokens may be |
|
119 |
* returned. For example, the pattern <tt>"\\s+"</tt> will return no empty |
|
120 |
* tokens since it matches multiple instances of the delimiter. The delimiting |
|
121 |
* pattern <tt>"\\s"</tt> could return empty tokens since it only passes one |
|
122 |
* space at a time. |
|
123 |
* |
|
124 |
* <p> A scanner can read text from any object which implements the {@link |
|
125 |
* java.lang.Readable} interface. If an invocation of the underlying |
|
126 |
* readable's {@link java.lang.Readable#read} method throws an {@link |
|
127 |
* java.io.IOException} then the scanner assumes that the end of the input |
|
128 |
* has been reached. The most recent <tt>IOException</tt> thrown by the |
|
129 |
* underlying readable can be retrieved via the {@link #ioException} method. |
|
130 |
* |
|
131 |
* <p>When a <code>Scanner</code> is closed, it will close its input source |
|
132 |
* if the source implements the {@link java.io.Closeable} interface. |
|
133 |
* |
|
134 |
* <p>A <code>Scanner</code> is not safe for multithreaded use without |
|
135 |
* external synchronization. |
|
136 |
* |
|
137 |
* <p>Unless otherwise mentioned, passing a <code>null</code> parameter into |
|
138 |
* any method of a <code>Scanner</code> will cause a |
|
139 |
* <code>NullPointerException</code> to be thrown. |
|
140 |
* |
|
141 |
* <p>A scanner will default to interpreting numbers as decimal unless a |
|
142 |
* different radix has been set by using the {@link #useRadix} method. The |
|
143 |
* {@link #reset} method will reset the value of the scanner's radix to |
|
144 |
* <code>10</code> regardless of whether it was previously changed. |
|
145 |
* |
|
146 |
* <a name="localized-numbers"> |
|
147 |
* <h4> Localized numbers </h4> |
|
148 |
* |
|
149 |
* <p> An instance of this class is capable of scanning numbers in the standard |
|
150 |
* formats as well as in the formats of the scanner's locale. A scanner's |
|
151 |
* <a name="initial-locale">initial locale </a>is the value returned by the {@link |
|
152 |
* java.util.Locale#getDefault} method; it may be changed via the {@link |
|
153 |
* #useLocale} method. The {@link #reset} method will reset the value of the |
|
154 |
* scanner's locale to the initial locale regardless of whether it was |
|
155 |
* previously changed. |
|
156 |
* |
|
157 |
* <p>The localized formats are defined in terms of the following parameters, |
|
158 |
* which for a particular locale are taken from that locale's {@link |
|
159 |
* java.text.DecimalFormat DecimalFormat} object, <tt>df</tt>, and its and |
|
160 |
* {@link java.text.DecimalFormatSymbols DecimalFormatSymbols} object, |
|
161 |
* <tt>dfs</tt>. |
|
162 |
* |
|
163 |
* <blockquote><table> |
|
164 |
* <tr><td valign="top"><i>LocalGroupSeparator </i></td> |
|
165 |
* <td valign="top">The character used to separate thousands groups, |
|
166 |
* <i>i.e.,</i> <tt>dfs.</tt>{@link |
|
167 |
* java.text.DecimalFormatSymbols#getGroupingSeparator |
|
168 |
* getGroupingSeparator()}</td></tr> |
|
169 |
* <tr><td valign="top"><i>LocalDecimalSeparator </i></td> |
|
170 |
* <td valign="top">The character used for the decimal point, |
|
171 |
* <i>i.e.,</i> <tt>dfs.</tt>{@link |
|
172 |
* java.text.DecimalFormatSymbols#getDecimalSeparator |
|
173 |
* getDecimalSeparator()}</td></tr> |
|
174 |
* <tr><td valign="top"><i>LocalPositivePrefix </i></td> |
|
175 |
* <td valign="top">The string that appears before a positive number (may |
|
176 |
* be empty), <i>i.e.,</i> <tt>df.</tt>{@link |
|
177 |
* java.text.DecimalFormat#getPositivePrefix |
|
178 |
* getPositivePrefix()}</td></tr> |
|
179 |
* <tr><td valign="top"><i>LocalPositiveSuffix </i></td> |
|
180 |
* <td valign="top">The string that appears after a positive number (may be |
|
181 |
* empty), <i>i.e.,</i> <tt>df.</tt>{@link |
|
182 |
* java.text.DecimalFormat#getPositiveSuffix |
|
183 |
* getPositiveSuffix()}</td></tr> |
|
184 |
* <tr><td valign="top"><i>LocalNegativePrefix </i></td> |
|
185 |
* <td valign="top">The string that appears before a negative number (may |
|
186 |
* be empty), <i>i.e.,</i> <tt>df.</tt>{@link |
|
187 |
* java.text.DecimalFormat#getNegativePrefix |
|
188 |
* getNegativePrefix()}</td></tr> |
|
189 |
* <tr><td valign="top"><i>LocalNegativeSuffix </i></td> |
|
190 |
* <td valign="top">The string that appears after a negative number (may be |
|
191 |
* empty), <i>i.e.,</i> <tt>df.</tt>{@link |
|
192 |
* java.text.DecimalFormat#getNegativeSuffix |
|
193 |
* getNegativeSuffix()}</td></tr> |
|
194 |
* <tr><td valign="top"><i>LocalNaN </i></td> |
|
195 |
* <td valign="top">The string that represents not-a-number for |
|
196 |
* floating-point values, |
|
197 |
* <i>i.e.,</i> <tt>dfs.</tt>{@link |
|
198 |
* java.text.DecimalFormatSymbols#getNaN |
|
199 |
* getNaN()}</td></tr> |
|
200 |
* <tr><td valign="top"><i>LocalInfinity </i></td> |
|
201 |
* <td valign="top">The string that represents infinity for floating-point |
|
202 |
* values, <i>i.e.,</i> <tt>dfs.</tt>{@link |
|
203 |
* java.text.DecimalFormatSymbols#getInfinity |
|
204 |
* getInfinity()}</td></tr> |
|
205 |
* </table></blockquote> |
|
206 |
* |
|
207 |
* <a name="number-syntax"> |
|
208 |
* <h4> Number syntax </h4> |
|
209 |
* |
|
210 |
* <p> The strings that can be parsed as numbers by an instance of this class |
|
211 |
* are specified in terms of the following regular-expression grammar, where |
|
212 |
* Rmax is the highest digit in the radix being used (for example, Rmax is 9 |
|
213 |
* in base 10). |
|
214 |
* |
|
215 |
* <p> |
|
216 |
* <table cellspacing=0 cellpadding=0 align=center> |
|
217 |
* |
|
218 |
* <tr><td valign=top align=right><i>NonASCIIDigit</i> ::</td> |
|
219 |
* <td valign=top>= A non-ASCII character c for which |
|
220 |
* {@link java.lang.Character#isDigit Character.isDigit}<tt>(c)</tt> |
|
221 |
* returns true</td></tr> |
|
222 |
* |
|
223 |
* <tr><td> </td></tr> |
|
224 |
* |
|
225 |
* <tr><td align=right><i>Non0Digit</i> ::</td> |
|
226 |
* <td><tt>= [1-</tt><i>Rmax</i><tt>] | </tt><i>NonASCIIDigit</i></td></tr> |
|
227 |
* |
|
228 |
* <tr><td> </td></tr> |
|
229 |
* |
|
230 |
* <tr><td align=right><i>Digit</i> ::</td> |
|
231 |
* <td><tt>= [0-</tt><i>Rmax</i><tt>] | </tt><i>NonASCIIDigit</i></td></tr> |
|
232 |
* |
|
233 |
* <tr><td> </td></tr> |
|
234 |
* |
|
235 |
* <tr><td valign=top align=right><i>GroupedNumeral</i> ::</td> |
|
236 |
* <td valign=top> |
|
237 |
* <table cellpadding=0 cellspacing=0> |
|
238 |
* <tr><td><tt>= ( </tt></td> |
|
239 |
* <td><i>Non0Digit</i><tt> |
|
240 |
* </tt><i>Digit</i><tt>? |
|
241 |
* </tt><i>Digit</i><tt>?</tt></td></tr> |
|
242 |
* <tr><td></td> |
|
243 |
* <td><tt>( </tt><i>LocalGroupSeparator</i><tt> |
|
244 |
* </tt><i>Digit</i><tt> |
|
245 |
* </tt><i>Digit</i><tt> |
|
246 |
* </tt><i>Digit</i><tt> )+ )</tt></td></tr> |
|
247 |
* </table></td></tr> |
|
248 |
* |
|
249 |
* <tr><td> </td></tr> |
|
250 |
* |
|
251 |
* <tr><td align=right><i>Numeral</i> ::</td> |
|
252 |
* <td><tt>= ( ( </tt><i>Digit</i><tt>+ ) |
|
253 |
* | </tt><i>GroupedNumeral</i><tt> )</tt></td></tr> |
|
254 |
* |
|
255 |
* <tr><td> </td></tr> |
|
256 |
* |
|
257 |
* <tr><td valign=top align=right> |
|
258 |
* <a name="Integer-regex"><i>Integer</i> ::</td> |
|
259 |
* <td valign=top><tt>= ( [-+]? ( </tt><i>Numeral</i><tt> |
|
260 |
* ) )</tt></td></tr> |
|
261 |
* <tr><td></td> |
|
262 |
* <td><tt>| </tt><i>LocalPositivePrefix</i><tt> </tt><i>Numeral</i><tt> |
|
263 |
* </tt><i>LocalPositiveSuffix</i></td></tr> |
|
264 |
* <tr><td></td> |
|
265 |
* <td><tt>| </tt><i>LocalNegativePrefix</i><tt> </tt><i>Numeral</i><tt> |
|
266 |
* </tt><i>LocalNegativeSuffix</i></td></tr> |
|
267 |
* |
|
268 |
* <tr><td> </td></tr> |
|
269 |
* |
|
270 |
* <tr><td align=right><i>DecimalNumeral</i> ::</td> |
|
271 |
* <td><tt>= </tt><i>Numeral</i></td></tr> |
|
272 |
* <tr><td></td> |
|
273 |
* <td><tt>| </tt><i>Numeral</i><tt> |
|
274 |
* </tt><i>LocalDecimalSeparator</i><tt> |
|
275 |
* </tt><i>Digit</i><tt>*</tt></td></tr> |
|
276 |
* <tr><td></td> |
|
277 |
* <td><tt>| </tt><i>LocalDecimalSeparator</i><tt> |
|
278 |
* </tt><i>Digit</i><tt>+</tt></td></tr> |
|
279 |
* |
|
280 |
* <tr><td> </td></tr> |
|
281 |
* |
|
282 |
* <tr><td align=right><i>Exponent</i> ::</td> |
|
283 |
* <td><tt>= ( [eE] [+-]? </tt><i>Digit</i><tt>+ )</tt></td></tr> |
|
284 |
* |
|
285 |
* <tr><td> </td></tr> |
|
286 |
* |
|
287 |
* <tr><td align=right> |
|
288 |
* <a name="Decimal-regex"><i>Decimal</i> ::</td> |
|
289 |
* <td><tt>= ( [-+]? </tt><i>DecimalNumeral</i><tt> |
|
290 |
* </tt><i>Exponent</i><tt>? )</tt></td></tr> |
|
291 |
* <tr><td></td> |
|
292 |
* <td><tt>| </tt><i>LocalPositivePrefix</i><tt> |
|
293 |
* </tt><i>DecimalNumeral</i><tt> |
|
294 |
* </tt><i>LocalPositiveSuffix</i> |
|
295 |
* </tt><i>Exponent</i><tt>?</td></tr> |
|
296 |
* <tr><td></td> |
|
297 |
* <td><tt>| </tt><i>LocalNegativePrefix</i><tt> |
|
298 |
* </tt><i>DecimalNumeral</i><tt> |
|
299 |
* </tt><i>LocalNegativeSuffix</i> |
|
300 |
* </tt><i>Exponent</i><tt>?</td></tr> |
|
301 |
* |
|
302 |
* <tr><td> </td></tr> |
|
303 |
* |
|
304 |
* <tr><td align=right><i>HexFloat</i> ::</td> |
|
305 |
* <td><tt>= [-+]? 0[xX][0-9a-fA-F]*\.[0-9a-fA-F]+ |
|
306 |
* ([pP][-+]?[0-9]+)?</tt></td></tr> |
|
307 |
* |
|
308 |
* <tr><td> </td></tr> |
|
309 |
* |
|
310 |
* <tr><td align=right><i>NonNumber</i> ::</td> |
|
311 |
* <td valign=top><tt>= NaN |
|
312 |
* | </tt><i>LocalNan</i><tt> |
|
313 |
* | Infinity |
|
314 |
* | </tt><i>LocalInfinity</i></td></tr> |
|
315 |
* |
|
316 |
* <tr><td> </td></tr> |
|
317 |
* |
|
318 |
* <tr><td align=right><i>SignedNonNumber</i> ::</td> |
|
319 |
* <td><tt>= ( [-+]? </tt><i>NonNumber</i><tt> )</tt></td></tr> |
|
320 |
* <tr><td></td> |
|
321 |
* <td><tt>| </tt><i>LocalPositivePrefix</i><tt> |
|
322 |
* </tt><i>NonNumber</i><tt> |
|
323 |
* </tt><i>LocalPositiveSuffix</i></td></tr> |
|
324 |
* <tr><td></td> |
|
325 |
* <td><tt>| </tt><i>LocalNegativePrefix</i><tt> |
|
326 |
* </tt><i>NonNumber</i><tt> |
|
327 |
* </tt><i>LocalNegativeSuffix</i></td></tr> |
|
328 |
* |
|
329 |
* <tr><td> </td></tr> |
|
330 |
* |
|
331 |
* <tr><td valign=top align=right> |
|
332 |
* <a name="Float-regex"><i>Float</i> ::</td> |
|
333 |
* <td valign=top><tt>= </tt><i>Decimal</i><tt></td></tr> |
|
334 |
* <tr><td></td> |
|
335 |
* <td><tt>| </tt><i>HexFloat</i><tt></td></tr> |
|
336 |
* <tr><td></td> |
|
337 |
* <td><tt>| </tt><i>SignedNonNumber</i><tt></td></tr> |
|
338 |
* |
|
339 |
* </table> |
|
340 |
* </center> |
|
341 |
* |
|
342 |
* <p> Whitespace is not significant in the above regular expressions. |
|
343 |
* |
|
344 |
* @since 1.5 |
|
345 |
*/ |
|
346 |
public final class Scanner implements Iterator<String> { |
|
347 |
||
348 |
// Internal buffer used to hold input |
|
349 |
private CharBuffer buf; |
|
350 |
||
351 |
// Size of internal character buffer |
|
352 |
private static final int BUFFER_SIZE = 1024; // change to 1024; |
|
353 |
||
354 |
// The index into the buffer currently held by the Scanner |
|
355 |
private int position; |
|
356 |
||
357 |
// Internal matcher used for finding delimiters |
|
358 |
private Matcher matcher; |
|
359 |
||
360 |
// Pattern used to delimit tokens |
|
361 |
private Pattern delimPattern; |
|
362 |
||
363 |
// Pattern found in last hasNext operation |
|
364 |
private Pattern hasNextPattern; |
|
365 |
||
366 |
// Position after last hasNext operation |
|
367 |
private int hasNextPosition; |
|
368 |
||
369 |
// Result after last hasNext operation |
|
370 |
private String hasNextResult; |
|
371 |
||
372 |
// The input source |
|
373 |
private Readable source; |
|
374 |
||
375 |
// Boolean is true if source is done |
|
376 |
private boolean sourceClosed = false; |
|
377 |
||
378 |
// Boolean indicating more input is required |
|
379 |
private boolean needInput = false; |
|
380 |
||
381 |
// Boolean indicating if a delim has been skipped this operation |
|
382 |
private boolean skipped = false; |
|
383 |
||
384 |
// A store of a position that the scanner may fall back to |
|
385 |
private int savedScannerPosition = -1; |
|
386 |
||
387 |
// A cache of the last primitive type scanned |
|
388 |
private Object typeCache = null; |
|
389 |
||
390 |
// Boolean indicating if a match result is available |
|
391 |
private boolean matchValid = false; |
|
392 |
||
393 |
// Boolean indicating if this scanner has been closed |
|
394 |
private boolean closed = false; |
|
395 |
||
396 |
// The current radix used by this scanner |
|
397 |
private int radix = 10; |
|
398 |
||
399 |
// The default radix for this scanner |
|
400 |
private int defaultRadix = 10; |
|
401 |
||
402 |
// The locale used by this scanner |
|
403 |
private Locale locale = null; |
|
404 |
||
405 |
// A cache of the last few recently used Patterns |
|
406 |
private LRUCache<String,Pattern> patternCache = |
|
407 |
new LRUCache<String,Pattern>(7) { |
|
408 |
protected Pattern create(String s) { |
|
409 |
return Pattern.compile(s); |
|
410 |
} |
|
411 |
protected boolean hasName(Pattern p, String s) { |
|
412 |
return p.pattern().equals(s); |
|
413 |
} |
|
414 |
}; |
|
415 |
||
416 |
// A holder of the last IOException encountered |
|
417 |
private IOException lastException; |
|
418 |
||
419 |
// A pattern for java whitespace |
|
420 |
private static Pattern WHITESPACE_PATTERN = Pattern.compile( |
|
421 |
"\\p{javaWhitespace}+"); |
|
422 |
||
423 |
// A pattern for any token |
|
424 |
private static Pattern FIND_ANY_PATTERN = Pattern.compile("(?s).*"); |
|
425 |
||
426 |
// A pattern for non-ASCII digits |
|
427 |
private static Pattern NON_ASCII_DIGIT = Pattern.compile( |
|
428 |
"[\\p{javaDigit}&&[^0-9]]"); |
|
429 |
||
430 |
// Fields and methods to support scanning primitive types |
|
431 |
||
432 |
/** |
|
433 |
* Locale dependent values used to scan numbers |
|
434 |
*/ |
|
435 |
private String groupSeparator = "\\,"; |
|
436 |
private String decimalSeparator = "\\."; |
|
437 |
private String nanString = "NaN"; |
|
438 |
private String infinityString = "Infinity"; |
|
439 |
private String positivePrefix = ""; |
|
440 |
private String negativePrefix = "\\-"; |
|
441 |
private String positiveSuffix = ""; |
|
442 |
private String negativeSuffix = ""; |
|
443 |
||
444 |
/** |
|
445 |
* Fields and an accessor method to match booleans |
|
446 |
*/ |
|
447 |
private static volatile Pattern boolPattern; |
|
448 |
private static final String BOOLEAN_PATTERN = "true|false"; |
|
449 |
private static Pattern boolPattern() { |
|
450 |
Pattern bp = boolPattern; |
|
451 |
if (bp == null) |
|
452 |
boolPattern = bp = Pattern.compile(BOOLEAN_PATTERN, |
|
453 |
Pattern.CASE_INSENSITIVE); |
|
454 |
return bp; |
|
455 |
} |
|
456 |
||
457 |
/** |
|
458 |
* Fields and methods to match bytes, shorts, ints, and longs |
|
459 |
*/ |
|
460 |
private Pattern integerPattern; |
|
461 |
private String digits = "0123456789abcdefghijklmnopqrstuvwxyz"; |
|
462 |
private String non0Digit = "[\\p{javaDigit}&&[^0]]"; |
|
463 |
private int SIMPLE_GROUP_INDEX = 5; |
|
464 |
private String buildIntegerPatternString() { |
|
465 |
String radixDigits = digits.substring(0, radix); |
|
466 |
// \\p{javaDigit} is not guaranteed to be appropriate |
|
467 |
// here but what can we do? The final authority will be |
|
468 |
// whatever parse method is invoked, so ultimately the |
|
469 |
// Scanner will do the right thing |
|
470 |
String digit = "((?i)["+radixDigits+"]|\\p{javaDigit})"; |
|
471 |
String groupedNumeral = "("+non0Digit+digit+"?"+digit+"?("+ |
|
472 |
groupSeparator+digit+digit+digit+")+)"; |
|
473 |
// digit++ is the possessive form which is necessary for reducing |
|
474 |
// backtracking that would otherwise cause unacceptable performance |
|
475 |
String numeral = "(("+ digit+"++)|"+groupedNumeral+")"; |
|
476 |
String javaStyleInteger = "([-+]?(" + numeral + "))"; |
|
477 |
String negativeInteger = negativePrefix + numeral + negativeSuffix; |
|
478 |
String positiveInteger = positivePrefix + numeral + positiveSuffix; |
|
479 |
return "("+ javaStyleInteger + ")|(" + |
|
480 |
positiveInteger + ")|(" + |
|
481 |
negativeInteger + ")"; |
|
482 |
} |
|
483 |
private Pattern integerPattern() { |
|
484 |
if (integerPattern == null) { |
|
485 |
integerPattern = patternCache.forName(buildIntegerPatternString()); |
|
486 |
} |
|
487 |
return integerPattern; |
|
488 |
} |
|
489 |
||
490 |
/** |
|
491 |
* Fields and an accessor method to match line separators |
|
492 |
*/ |
|
493 |
private static volatile Pattern separatorPattern; |
|
494 |
private static volatile Pattern linePattern; |
|
495 |
private static final String LINE_SEPARATOR_PATTERN = |
|
496 |
"\r\n|[\n\r\u2028\u2029\u0085]"; |
|
497 |
private static final String LINE_PATTERN = ".*("+LINE_SEPARATOR_PATTERN+")|.+$"; |
|
498 |
||
499 |
private static Pattern separatorPattern() { |
|
500 |
Pattern sp = separatorPattern; |
|
501 |
if (sp == null) |
|
502 |
separatorPattern = sp = Pattern.compile(LINE_SEPARATOR_PATTERN); |
|
503 |
return sp; |
|
504 |
} |
|
505 |
||
506 |
private static Pattern linePattern() { |
|
507 |
Pattern lp = linePattern; |
|
508 |
if (lp == null) |
|
509 |
linePattern = lp = Pattern.compile(LINE_PATTERN); |
|
510 |
return lp; |
|
511 |
} |
|
512 |
||
513 |
/** |
|
514 |
* Fields and methods to match floats and doubles |
|
515 |
*/ |
|
516 |
private Pattern floatPattern; |
|
517 |
private Pattern decimalPattern; |
|
518 |
private void buildFloatAndDecimalPattern() { |
|
519 |
// \\p{javaDigit} may not be perfect, see above |
|
520 |
String digit = "([0-9]|(\\p{javaDigit}))"; |
|
521 |
String exponent = "([eE][+-]?"+digit+"+)?"; |
|
522 |
String groupedNumeral = "("+non0Digit+digit+"?"+digit+"?("+ |
|
523 |
groupSeparator+digit+digit+digit+")+)"; |
|
524 |
// Once again digit++ is used for performance, as above |
|
525 |
String numeral = "(("+digit+"++)|"+groupedNumeral+")"; |
|
526 |
String decimalNumeral = "("+numeral+"|"+numeral + |
|
527 |
decimalSeparator + digit + "*+|"+ decimalSeparator + |
|
528 |
digit + "++)"; |
|
529 |
String nonNumber = "(NaN|"+nanString+"|Infinity|"+ |
|
530 |
infinityString+")"; |
|
531 |
String positiveFloat = "(" + positivePrefix + decimalNumeral + |
|
532 |
positiveSuffix + exponent + ")"; |
|
533 |
String negativeFloat = "(" + negativePrefix + decimalNumeral + |
|
534 |
negativeSuffix + exponent + ")"; |
|
535 |
String decimal = "(([-+]?" + decimalNumeral + exponent + ")|"+ |
|
536 |
positiveFloat + "|" + negativeFloat + ")"; |
|
537 |
String hexFloat = |
|
538 |
"[-+]?0[xX][0-9a-fA-F]*\\.[0-9a-fA-F]+([pP][-+]?[0-9]+)?"; |
|
539 |
String positiveNonNumber = "(" + positivePrefix + nonNumber + |
|
540 |
positiveSuffix + ")"; |
|
541 |
String negativeNonNumber = "(" + negativePrefix + nonNumber + |
|
542 |
negativeSuffix + ")"; |
|
543 |
String signedNonNumber = "(([-+]?"+nonNumber+")|" + |
|
544 |
positiveNonNumber + "|" + |
|
545 |
negativeNonNumber + ")"; |
|
546 |
floatPattern = Pattern.compile(decimal + "|" + hexFloat + "|" + |
|
547 |
signedNonNumber); |
|
548 |
decimalPattern = Pattern.compile(decimal); |
|
549 |
} |
|
550 |
private Pattern floatPattern() { |
|
551 |
if (floatPattern == null) { |
|
552 |
buildFloatAndDecimalPattern(); |
|
553 |
} |
|
554 |
return floatPattern; |
|
555 |
} |
|
556 |
private Pattern decimalPattern() { |
|
557 |
if (decimalPattern == null) { |
|
558 |
buildFloatAndDecimalPattern(); |
|
559 |
} |
|
560 |
return decimalPattern; |
|
561 |
} |
|
562 |
||
563 |
// Constructors |
|
564 |
||
565 |
/** |
|
566 |
* Constructs a <code>Scanner</code> that returns values scanned |
|
567 |
* from the specified source delimited by the specified pattern. |
|
568 |
* |
|
569 |
* @param source A character source implementing the Readable interface |
|
570 |
* @param pattern A delimiting pattern |
|
571 |
* @return A scanner with the specified source and pattern |
|
572 |
*/ |
|
573 |
private Scanner(Readable source, Pattern pattern) { |
|
574 |
if (source == null) |
|
575 |
throw new NullPointerException("source"); |
|
576 |
if (pattern == null) |
|
577 |
throw new NullPointerException("pattern"); |
|
578 |
this.source = source; |
|
579 |
delimPattern = pattern; |
|
580 |
buf = CharBuffer.allocate(BUFFER_SIZE); |
|
581 |
buf.limit(0); |
|
582 |
matcher = delimPattern.matcher(buf); |
|
583 |
matcher.useTransparentBounds(true); |
|
584 |
matcher.useAnchoringBounds(false); |
|
585 |
useLocale(Locale.getDefault()); |
|
586 |
} |
|
587 |
||
588 |
/** |
|
589 |
* Constructs a new <code>Scanner</code> that produces values scanned |
|
590 |
* from the specified source. |
|
591 |
* |
|
592 |
* @param source A character source implementing the {@link Readable} |
|
593 |
* interface |
|
594 |
*/ |
|
595 |
public Scanner(Readable source) { |
|
596 |
this(source, WHITESPACE_PATTERN); |
|
597 |
} |
|
598 |
||
599 |
/** |
|
600 |
* Constructs a new <code>Scanner</code> that produces values scanned |
|
601 |
* from the specified input stream. Bytes from the stream are converted |
|
602 |
* into characters using the underlying platform's |
|
603 |
* {@linkplain java.nio.charset.Charset#defaultCharset() default charset}. |
|
604 |
* |
|
605 |
* @param source An input stream to be scanned |
|
606 |
*/ |
|
607 |
public Scanner(InputStream source) { |
|
608 |
this(new InputStreamReader(source), WHITESPACE_PATTERN); |
|
609 |
} |
|
610 |
||
611 |
/** |
|
612 |
* Constructs a new <code>Scanner</code> that produces values scanned |
|
613 |
* from the specified input stream. Bytes from the stream are converted |
|
614 |
* into characters using the specified charset. |
|
615 |
* |
|
616 |
* @param source An input stream to be scanned |
|
617 |
* @param charsetName The encoding type used to convert bytes from the |
|
618 |
* stream into characters to be scanned |
|
619 |
* @throws IllegalArgumentException if the specified character set |
|
620 |
* does not exist |
|
621 |
*/ |
|
622 |
public Scanner(InputStream source, String charsetName) { |
|
623 |
this(makeReadable(source, charsetName), WHITESPACE_PATTERN); |
|
624 |
} |
|
625 |
||
626 |
private static Readable makeReadable(InputStream source, |
|
627 |
String charsetName) |
|
628 |
{ |
|
629 |
if (source == null) |
|
630 |
throw new NullPointerException("source"); |
|
631 |
InputStreamReader isr = null; |
|
632 |
try { |
|
633 |
isr = new InputStreamReader(source, charsetName); |
|
634 |
} catch (UnsupportedEncodingException uee) { |
|
635 |
IllegalArgumentException iae = new IllegalArgumentException(); |
|
636 |
iae.initCause(uee); |
|
637 |
throw iae; |
|
638 |
} |
|
639 |
return isr; |
|
640 |
} |
|
641 |
||
642 |
/** |
|
643 |
* Constructs a new <code>Scanner</code> that produces values scanned |
|
644 |
* from the specified file. Bytes from the file are converted into |
|
645 |
* characters using the underlying platform's |
|
646 |
* {@linkplain java.nio.charset.Charset#defaultCharset() default charset}. |
|
647 |
* |
|
648 |
* @param source A file to be scanned |
|
649 |
* @throws FileNotFoundException if source is not found |
|
650 |
*/ |
|
651 |
public Scanner(File source) |
|
652 |
throws FileNotFoundException |
|
653 |
{ |
|
654 |
this((ReadableByteChannel)(new FileInputStream(source).getChannel())); |
|
655 |
} |
|
656 |
||
657 |
/** |
|
658 |
* Constructs a new <code>Scanner</code> that produces values scanned |
|
659 |
* from the specified file. Bytes from the file are converted into |
|
660 |
* characters using the specified charset. |
|
661 |
* |
|
662 |
* @param source A file to be scanned |
|
663 |
* @param charsetName The encoding type used to convert bytes from the file |
|
664 |
* into characters to be scanned |
|
665 |
* @throws FileNotFoundException if source is not found |
|
666 |
* @throws IllegalArgumentException if the specified encoding is |
|
667 |
* not found |
|
668 |
*/ |
|
669 |
public Scanner(File source, String charsetName) |
|
670 |
throws FileNotFoundException |
|
671 |
{ |
|
672 |
this((ReadableByteChannel)(new FileInputStream(source).getChannel()), |
|
673 |
charsetName); |
|
674 |
} |
|
675 |
||
676 |
/** |
|
2057
3acf8e5e2ca0
6781363: New I/O: Update socket-channel API to jsr203/nio2-b99
alanb
parents:
2
diff
changeset
|
677 |
* {@note new} |
3acf8e5e2ca0
6781363: New I/O: Update socket-channel API to jsr203/nio2-b99
alanb
parents:
2
diff
changeset
|
678 |
* Constructs a new <code>Scanner</code> that produces values scanned |
3acf8e5e2ca0
6781363: New I/O: Update socket-channel API to jsr203/nio2-b99
alanb
parents:
2
diff
changeset
|
679 |
* from the specified file. Bytes from the file are converted into |
3acf8e5e2ca0
6781363: New I/O: Update socket-channel API to jsr203/nio2-b99
alanb
parents:
2
diff
changeset
|
680 |
* characters using the underlying platform's |
3acf8e5e2ca0
6781363: New I/O: Update socket-channel API to jsr203/nio2-b99
alanb
parents:
2
diff
changeset
|
681 |
* {@linkplain java.nio.charset.Charset#defaultCharset() default charset}. |
3acf8e5e2ca0
6781363: New I/O: Update socket-channel API to jsr203/nio2-b99
alanb
parents:
2
diff
changeset
|
682 |
* |
3acf8e5e2ca0
6781363: New I/O: Update socket-channel API to jsr203/nio2-b99
alanb
parents:
2
diff
changeset
|
683 |
* @param source |
3acf8e5e2ca0
6781363: New I/O: Update socket-channel API to jsr203/nio2-b99
alanb
parents:
2
diff
changeset
|
684 |
* A file to be scanned |
3acf8e5e2ca0
6781363: New I/O: Update socket-channel API to jsr203/nio2-b99
alanb
parents:
2
diff
changeset
|
685 |
* @throws IOException |
3acf8e5e2ca0
6781363: New I/O: Update socket-channel API to jsr203/nio2-b99
alanb
parents:
2
diff
changeset
|
686 |
* if an I/O error occurs opening source |
3acf8e5e2ca0
6781363: New I/O: Update socket-channel API to jsr203/nio2-b99
alanb
parents:
2
diff
changeset
|
687 |
* |
3acf8e5e2ca0
6781363: New I/O: Update socket-channel API to jsr203/nio2-b99
alanb
parents:
2
diff
changeset
|
688 |
* @since 1.7 |
3acf8e5e2ca0
6781363: New I/O: Update socket-channel API to jsr203/nio2-b99
alanb
parents:
2
diff
changeset
|
689 |
*/ |
3acf8e5e2ca0
6781363: New I/O: Update socket-channel API to jsr203/nio2-b99
alanb
parents:
2
diff
changeset
|
690 |
public Scanner(FileRef source) |
3acf8e5e2ca0
6781363: New I/O: Update socket-channel API to jsr203/nio2-b99
alanb
parents:
2
diff
changeset
|
691 |
throws IOException |
3acf8e5e2ca0
6781363: New I/O: Update socket-channel API to jsr203/nio2-b99
alanb
parents:
2
diff
changeset
|
692 |
{ |
3065
452aaa2899fc
6838333: New I/O: Update file system API to jsr203/nio2-b101
alanb
parents:
2057
diff
changeset
|
693 |
this(source.newInputStream()); |
2057
3acf8e5e2ca0
6781363: New I/O: Update socket-channel API to jsr203/nio2-b99
alanb
parents:
2
diff
changeset
|
694 |
} |
3acf8e5e2ca0
6781363: New I/O: Update socket-channel API to jsr203/nio2-b99
alanb
parents:
2
diff
changeset
|
695 |
|
3acf8e5e2ca0
6781363: New I/O: Update socket-channel API to jsr203/nio2-b99
alanb
parents:
2
diff
changeset
|
696 |
/** |
3acf8e5e2ca0
6781363: New I/O: Update socket-channel API to jsr203/nio2-b99
alanb
parents:
2
diff
changeset
|
697 |
* {@note new} |
3acf8e5e2ca0
6781363: New I/O: Update socket-channel API to jsr203/nio2-b99
alanb
parents:
2
diff
changeset
|
698 |
* Constructs a new <code>Scanner</code> that produces values scanned |
3acf8e5e2ca0
6781363: New I/O: Update socket-channel API to jsr203/nio2-b99
alanb
parents:
2
diff
changeset
|
699 |
* from the specified file. Bytes from the file are converted into |
3acf8e5e2ca0
6781363: New I/O: Update socket-channel API to jsr203/nio2-b99
alanb
parents:
2
diff
changeset
|
700 |
* characters using the specified charset. |
3acf8e5e2ca0
6781363: New I/O: Update socket-channel API to jsr203/nio2-b99
alanb
parents:
2
diff
changeset
|
701 |
* |
3acf8e5e2ca0
6781363: New I/O: Update socket-channel API to jsr203/nio2-b99
alanb
parents:
2
diff
changeset
|
702 |
* @param source |
3acf8e5e2ca0
6781363: New I/O: Update socket-channel API to jsr203/nio2-b99
alanb
parents:
2
diff
changeset
|
703 |
* A file to be scanned |
3acf8e5e2ca0
6781363: New I/O: Update socket-channel API to jsr203/nio2-b99
alanb
parents:
2
diff
changeset
|
704 |
* @param charsetName |
3acf8e5e2ca0
6781363: New I/O: Update socket-channel API to jsr203/nio2-b99
alanb
parents:
2
diff
changeset
|
705 |
* The encoding type used to convert bytes from the file |
3acf8e5e2ca0
6781363: New I/O: Update socket-channel API to jsr203/nio2-b99
alanb
parents:
2
diff
changeset
|
706 |
* into characters to be scanned |
3acf8e5e2ca0
6781363: New I/O: Update socket-channel API to jsr203/nio2-b99
alanb
parents:
2
diff
changeset
|
707 |
* @throws IOException |
3acf8e5e2ca0
6781363: New I/O: Update socket-channel API to jsr203/nio2-b99
alanb
parents:
2
diff
changeset
|
708 |
* if an I/O error occurs opening source |
3acf8e5e2ca0
6781363: New I/O: Update socket-channel API to jsr203/nio2-b99
alanb
parents:
2
diff
changeset
|
709 |
* @throws IllegalArgumentException |
3acf8e5e2ca0
6781363: New I/O: Update socket-channel API to jsr203/nio2-b99
alanb
parents:
2
diff
changeset
|
710 |
* if the specified encoding is not found |
3acf8e5e2ca0
6781363: New I/O: Update socket-channel API to jsr203/nio2-b99
alanb
parents:
2
diff
changeset
|
711 |
* @since 1.7 |
3acf8e5e2ca0
6781363: New I/O: Update socket-channel API to jsr203/nio2-b99
alanb
parents:
2
diff
changeset
|
712 |
*/ |
3acf8e5e2ca0
6781363: New I/O: Update socket-channel API to jsr203/nio2-b99
alanb
parents:
2
diff
changeset
|
713 |
public Scanner(FileRef source, String charsetName) |
3acf8e5e2ca0
6781363: New I/O: Update socket-channel API to jsr203/nio2-b99
alanb
parents:
2
diff
changeset
|
714 |
throws IOException |
3acf8e5e2ca0
6781363: New I/O: Update socket-channel API to jsr203/nio2-b99
alanb
parents:
2
diff
changeset
|
715 |
{ |
3065
452aaa2899fc
6838333: New I/O: Update file system API to jsr203/nio2-b101
alanb
parents:
2057
diff
changeset
|
716 |
this(source.newInputStream(), charsetName); |
2057
3acf8e5e2ca0
6781363: New I/O: Update socket-channel API to jsr203/nio2-b99
alanb
parents:
2
diff
changeset
|
717 |
} |
3acf8e5e2ca0
6781363: New I/O: Update socket-channel API to jsr203/nio2-b99
alanb
parents:
2
diff
changeset
|
718 |
|
3acf8e5e2ca0
6781363: New I/O: Update socket-channel API to jsr203/nio2-b99
alanb
parents:
2
diff
changeset
|
719 |
/** |
2 | 720 |
* Constructs a new <code>Scanner</code> that produces values scanned |
721 |
* from the specified string. |
|
722 |
* |
|
723 |
* @param source A string to scan |
|
724 |
*/ |
|
725 |
public Scanner(String source) { |
|
726 |
this(new StringReader(source), WHITESPACE_PATTERN); |
|
727 |
} |
|
728 |
||
729 |
/** |
|
730 |
* Constructs a new <code>Scanner</code> that produces values scanned |
|
731 |
* from the specified channel. Bytes from the source are converted into |
|
732 |
* characters using the underlying platform's |
|
733 |
* {@linkplain java.nio.charset.Charset#defaultCharset() default charset}. |
|
734 |
* |
|
735 |
* @param source A channel to scan |
|
736 |
*/ |
|
737 |
public Scanner(ReadableByteChannel source) { |
|
738 |
this(makeReadable(source), WHITESPACE_PATTERN); |
|
739 |
} |
|
740 |
||
741 |
private static Readable makeReadable(ReadableByteChannel source) { |
|
742 |
if (source == null) |
|
743 |
throw new NullPointerException("source"); |
|
744 |
String defaultCharsetName = |
|
745 |
java.nio.charset.Charset.defaultCharset().name(); |
|
746 |
return Channels.newReader(source, |
|
747 |
java.nio.charset.Charset.defaultCharset().name()); |
|
748 |
} |
|
749 |
||
750 |
/** |
|
751 |
* Constructs a new <code>Scanner</code> that produces values scanned |
|
752 |
* from the specified channel. Bytes from the source are converted into |
|
753 |
* characters using the specified charset. |
|
754 |
* |
|
755 |
* @param source A channel to scan |
|
756 |
* @param charsetName The encoding type used to convert bytes from the |
|
757 |
* channel into characters to be scanned |
|
758 |
* @throws IllegalArgumentException if the specified character set |
|
759 |
* does not exist |
|
760 |
*/ |
|
761 |
public Scanner(ReadableByteChannel source, String charsetName) { |
|
762 |
this(makeReadable(source, charsetName), WHITESPACE_PATTERN); |
|
763 |
} |
|
764 |
||
765 |
private static Readable makeReadable(ReadableByteChannel source, |
|
766 |
String charsetName) |
|
767 |
{ |
|
768 |
if (source == null) |
|
769 |
throw new NullPointerException("source"); |
|
770 |
if (!Charset.isSupported(charsetName)) |
|
771 |
throw new IllegalArgumentException(charsetName); |
|
772 |
return Channels.newReader(source, charsetName); |
|
773 |
} |
|
774 |
||
775 |
// Private primitives used to support scanning |
|
776 |
||
777 |
private void saveState() { |
|
778 |
savedScannerPosition = position; |
|
779 |
} |
|
780 |
||
781 |
private void revertState() { |
|
782 |
this.position = savedScannerPosition; |
|
783 |
savedScannerPosition = -1; |
|
784 |
skipped = false; |
|
785 |
} |
|
786 |
||
787 |
private boolean revertState(boolean b) { |
|
788 |
this.position = savedScannerPosition; |
|
789 |
savedScannerPosition = -1; |
|
790 |
skipped = false; |
|
791 |
return b; |
|
792 |
} |
|
793 |
||
794 |
private void cacheResult() { |
|
795 |
hasNextResult = matcher.group(); |
|
796 |
hasNextPosition = matcher.end(); |
|
797 |
hasNextPattern = matcher.pattern(); |
|
798 |
} |
|
799 |
||
800 |
private void cacheResult(String result) { |
|
801 |
hasNextResult = result; |
|
802 |
hasNextPosition = matcher.end(); |
|
803 |
hasNextPattern = matcher.pattern(); |
|
804 |
} |
|
805 |
||
806 |
// Clears both regular cache and type cache |
|
807 |
private void clearCaches() { |
|
808 |
hasNextPattern = null; |
|
809 |
typeCache = null; |
|
810 |
} |
|
811 |
||
812 |
// Also clears both the regular cache and the type cache |
|
813 |
private String getCachedResult() { |
|
814 |
position = hasNextPosition; |
|
815 |
hasNextPattern = null; |
|
816 |
typeCache = null; |
|
817 |
return hasNextResult; |
|
818 |
} |
|
819 |
||
820 |
// Also clears both the regular cache and the type cache |
|
821 |
private void useTypeCache() { |
|
822 |
if (closed) |
|
823 |
throw new IllegalStateException("Scanner closed"); |
|
824 |
position = hasNextPosition; |
|
825 |
hasNextPattern = null; |
|
826 |
typeCache = null; |
|
827 |
} |
|
828 |
||
829 |
// Tries to read more input. May block. |
|
830 |
private void readInput() { |
|
831 |
if (buf.limit() == buf.capacity()) |
|
832 |
makeSpace(); |
|
833 |
||
834 |
// Prepare to receive data |
|
835 |
int p = buf.position(); |
|
836 |
buf.position(buf.limit()); |
|
837 |
buf.limit(buf.capacity()); |
|
838 |
||
839 |
int n = 0; |
|
840 |
try { |
|
841 |
n = source.read(buf); |
|
842 |
} catch (IOException ioe) { |
|
843 |
lastException = ioe; |
|
844 |
n = -1; |
|
845 |
} |
|
846 |
||
847 |
if (n == -1) { |
|
848 |
sourceClosed = true; |
|
849 |
needInput = false; |
|
850 |
} |
|
851 |
||
852 |
if (n > 0) |
|
853 |
needInput = false; |
|
854 |
||
855 |
// Restore current position and limit for reading |
|
856 |
buf.limit(buf.position()); |
|
857 |
buf.position(p); |
|
858 |
} |
|
859 |
||
860 |
// After this method is called there will either be an exception |
|
861 |
// or else there will be space in the buffer |
|
862 |
private boolean makeSpace() { |
|
863 |
clearCaches(); |
|
864 |
int offset = savedScannerPosition == -1 ? |
|
865 |
position : savedScannerPosition; |
|
866 |
buf.position(offset); |
|
867 |
// Gain space by compacting buffer |
|
868 |
if (offset > 0) { |
|
869 |
buf.compact(); |
|
870 |
translateSavedIndexes(offset); |
|
871 |
position -= offset; |
|
872 |
buf.flip(); |
|
873 |
return true; |
|
874 |
} |
|
875 |
// Gain space by growing buffer |
|
876 |
int newSize = buf.capacity() * 2; |
|
877 |
CharBuffer newBuf = CharBuffer.allocate(newSize); |
|
878 |
newBuf.put(buf); |
|
879 |
newBuf.flip(); |
|
880 |
translateSavedIndexes(offset); |
|
881 |
position -= offset; |
|
882 |
buf = newBuf; |
|
883 |
matcher.reset(buf); |
|
884 |
return true; |
|
885 |
} |
|
886 |
||
887 |
// When a buffer compaction/reallocation occurs the saved indexes must |
|
888 |
// be modified appropriately |
|
889 |
private void translateSavedIndexes(int offset) { |
|
890 |
if (savedScannerPosition != -1) |
|
891 |
savedScannerPosition -= offset; |
|
892 |
} |
|
893 |
||
894 |
// If we are at the end of input then NoSuchElement; |
|
895 |
// If there is still input left then InputMismatch |
|
896 |
private void throwFor() { |
|
897 |
skipped = false; |
|
898 |
if ((sourceClosed) && (position == buf.limit())) |
|
899 |
throw new NoSuchElementException(); |
|
900 |
else |
|
901 |
throw new InputMismatchException(); |
|
902 |
} |
|
903 |
||
904 |
// Returns true if a complete token or partial token is in the buffer. |
|
905 |
// It is not necessary to find a complete token since a partial token |
|
906 |
// means that there will be another token with or without more input. |
|
907 |
private boolean hasTokenInBuffer() { |
|
908 |
matchValid = false; |
|
909 |
matcher.usePattern(delimPattern); |
|
910 |
matcher.region(position, buf.limit()); |
|
911 |
||
912 |
// Skip delims first |
|
913 |
if (matcher.lookingAt()) |
|
914 |
position = matcher.end(); |
|
915 |
||
916 |
// If we are sitting at the end, no more tokens in buffer |
|
917 |
if (position == buf.limit()) |
|
918 |
return false; |
|
919 |
||
920 |
return true; |
|
921 |
} |
|
922 |
||
923 |
/* |
|
924 |
* Returns a "complete token" that matches the specified pattern |
|
925 |
* |
|
926 |
* A token is complete if surrounded by delims; a partial token |
|
927 |
* is prefixed by delims but not postfixed by them |
|
928 |
* |
|
929 |
* The position is advanced to the end of that complete token |
|
930 |
* |
|
931 |
* Pattern == null means accept any token at all |
|
932 |
* |
|
933 |
* Triple return: |
|
934 |
* 1. valid string means it was found |
|
935 |
* 2. null with needInput=false means we won't ever find it |
|
936 |
* 3. null with needInput=true means try again after readInput |
|
937 |
*/ |
|
938 |
private String getCompleteTokenInBuffer(Pattern pattern) { |
|
939 |
matchValid = false; |
|
940 |
||
941 |
// Skip delims first |
|
942 |
matcher.usePattern(delimPattern); |
|
943 |
if (!skipped) { // Enforcing only one skip of leading delims |
|
944 |
matcher.region(position, buf.limit()); |
|
945 |
if (matcher.lookingAt()) { |
|
946 |
// If more input could extend the delimiters then we must wait |
|
947 |
// for more input |
|
948 |
if (matcher.hitEnd() && !sourceClosed) { |
|
949 |
needInput = true; |
|
950 |
return null; |
|
951 |
} |
|
952 |
// The delims were whole and the matcher should skip them |
|
953 |
skipped = true; |
|
954 |
position = matcher.end(); |
|
955 |
} |
|
956 |
} |
|
957 |
||
958 |
// If we are sitting at the end, no more tokens in buffer |
|
959 |
if (position == buf.limit()) { |
|
960 |
if (sourceClosed) |
|
961 |
return null; |
|
962 |
needInput = true; |
|
963 |
return null; |
|
964 |
} |
|
965 |
||
966 |
// Must look for next delims. Simply attempting to match the |
|
967 |
// pattern at this point may find a match but it might not be |
|
968 |
// the first longest match because of missing input, or it might |
|
969 |
// match a partial token instead of the whole thing. |
|
970 |
||
971 |
// Then look for next delims |
|
972 |
matcher.region(position, buf.limit()); |
|
973 |
boolean foundNextDelim = matcher.find(); |
|
974 |
if (foundNextDelim && (matcher.end() == position)) { |
|
975 |
// Zero length delimiter match; we should find the next one |
|
976 |
// using the automatic advance past a zero length match; |
|
977 |
// Otherwise we have just found the same one we just skipped |
|
978 |
foundNextDelim = matcher.find(); |
|
979 |
} |
|
980 |
if (foundNextDelim) { |
|
981 |
// In the rare case that more input could cause the match |
|
982 |
// to be lost and there is more input coming we must wait |
|
983 |
// for more input. Note that hitting the end is okay as long |
|
984 |
// as the match cannot go away. It is the beginning of the |
|
985 |
// next delims we want to be sure about, we don't care if |
|
986 |
// they potentially extend further. |
|
987 |
if (matcher.requireEnd() && !sourceClosed) { |
|
988 |
needInput = true; |
|
989 |
return null; |
|
990 |
} |
|
991 |
int tokenEnd = matcher.start(); |
|
992 |
// There is a complete token. |
|
993 |
if (pattern == null) { |
|
994 |
// Must continue with match to provide valid MatchResult |
|
995 |
pattern = FIND_ANY_PATTERN; |
|
996 |
} |
|
997 |
// Attempt to match against the desired pattern |
|
998 |
matcher.usePattern(pattern); |
|
999 |
matcher.region(position, tokenEnd); |
|
1000 |
if (matcher.matches()) { |
|
1001 |
String s = matcher.group(); |
|
1002 |
position = matcher.end(); |
|
1003 |
return s; |
|
1004 |
} else { // Complete token but it does not match |
|
1005 |
return null; |
|
1006 |
} |
|
1007 |
} |
|
1008 |
||
1009 |
// If we can't find the next delims but no more input is coming, |
|
1010 |
// then we can treat the remainder as a whole token |
|
1011 |
if (sourceClosed) { |
|
1012 |
if (pattern == null) { |
|
1013 |
// Must continue with match to provide valid MatchResult |
|
1014 |
pattern = FIND_ANY_PATTERN; |
|
1015 |
} |
|
1016 |
// Last token; Match the pattern here or throw |
|
1017 |
matcher.usePattern(pattern); |
|
1018 |
matcher.region(position, buf.limit()); |
|
1019 |
if (matcher.matches()) { |
|
1020 |
String s = matcher.group(); |
|
1021 |
position = matcher.end(); |
|
1022 |
return s; |
|
1023 |
} |
|
1024 |
// Last piece does not match |
|
1025 |
return null; |
|
1026 |
} |
|
1027 |
||
1028 |
// There is a partial token in the buffer; must read more |
|
1029 |
// to complete it |
|
1030 |
needInput = true; |
|
1031 |
return null; |
|
1032 |
} |
|
1033 |
||
1034 |
// Finds the specified pattern in the buffer up to horizon. |
|
1035 |
// Returns a match for the specified input pattern. |
|
1036 |
private String findPatternInBuffer(Pattern pattern, int horizon) { |
|
1037 |
matchValid = false; |
|
1038 |
matcher.usePattern(pattern); |
|
1039 |
int bufferLimit = buf.limit(); |
|
1040 |
int horizonLimit = -1; |
|
1041 |
int searchLimit = bufferLimit; |
|
1042 |
if (horizon > 0) { |
|
1043 |
horizonLimit = position + horizon; |
|
1044 |
if (horizonLimit < bufferLimit) |
|
1045 |
searchLimit = horizonLimit; |
|
1046 |
} |
|
1047 |
matcher.region(position, searchLimit); |
|
1048 |
if (matcher.find()) { |
|
1049 |
if (matcher.hitEnd() && (!sourceClosed)) { |
|
1050 |
// The match may be longer if didn't hit horizon or real end |
|
1051 |
if (searchLimit != horizonLimit) { |
|
1052 |
// Hit an artificial end; try to extend the match |
|
1053 |
needInput = true; |
|
1054 |
return null; |
|
1055 |
} |
|
1056 |
// The match could go away depending on what is next |
|
1057 |
if ((searchLimit == horizonLimit) && matcher.requireEnd()) { |
|
1058 |
// Rare case: we hit the end of input and it happens |
|
1059 |
// that it is at the horizon and the end of input is |
|
1060 |
// required for the match. |
|
1061 |
needInput = true; |
|
1062 |
return null; |
|
1063 |
} |
|
1064 |
} |
|
1065 |
// Did not hit end, or hit real end, or hit horizon |
|
1066 |
position = matcher.end(); |
|
1067 |
return matcher.group(); |
|
1068 |
} |
|
1069 |
||
1070 |
if (sourceClosed) |
|
1071 |
return null; |
|
1072 |
||
1073 |
// If there is no specified horizon, or if we have not searched |
|
1074 |
// to the specified horizon yet, get more input |
|
1075 |
if ((horizon == 0) || (searchLimit != horizonLimit)) |
|
1076 |
needInput = true; |
|
1077 |
return null; |
|
1078 |
} |
|
1079 |
||
1080 |
// Returns a match for the specified input pattern anchored at |
|
1081 |
// the current position |
|
1082 |
private String matchPatternInBuffer(Pattern pattern) { |
|
1083 |
matchValid = false; |
|
1084 |
matcher.usePattern(pattern); |
|
1085 |
matcher.region(position, buf.limit()); |
|
1086 |
if (matcher.lookingAt()) { |
|
1087 |
if (matcher.hitEnd() && (!sourceClosed)) { |
|
1088 |
// Get more input and try again |
|
1089 |
needInput = true; |
|
1090 |
return null; |
|
1091 |
} |
|
1092 |
position = matcher.end(); |
|
1093 |
return matcher.group(); |
|
1094 |
} |
|
1095 |
||
1096 |
if (sourceClosed) |
|
1097 |
return null; |
|
1098 |
||
1099 |
// Read more to find pattern |
|
1100 |
needInput = true; |
|
1101 |
return null; |
|
1102 |
} |
|
1103 |
||
1104 |
// Throws if the scanner is closed |
|
1105 |
private void ensureOpen() { |
|
1106 |
if (closed) |
|
1107 |
throw new IllegalStateException("Scanner closed"); |
|
1108 |
} |
|
1109 |
||
1110 |
// Public methods |
|
1111 |
||
1112 |
/** |
|
1113 |
* Closes this scanner. |
|
1114 |
* |
|
1115 |
* <p> If this scanner has not yet been closed then if its underlying |
|
1116 |
* {@linkplain java.lang.Readable readable} also implements the {@link |
|
1117 |
* java.io.Closeable} interface then the readable's <tt>close</tt> method |
|
1118 |
* will be invoked. If this scanner is already closed then invoking this |
|
1119 |
* method will have no effect. |
|
1120 |
* |
|
1121 |
* <p>Attempting to perform search operations after a scanner has |
|
1122 |
* been closed will result in an {@link IllegalStateException}. |
|
1123 |
* |
|
1124 |
*/ |
|
1125 |
public void close() { |
|
1126 |
if (closed) |
|
1127 |
return; |
|
1128 |
if (source instanceof Closeable) { |
|
1129 |
try { |
|
1130 |
((Closeable)source).close(); |
|
1131 |
} catch (IOException ioe) { |
|
1132 |
lastException = ioe; |
|
1133 |
} |
|
1134 |
} |
|
1135 |
sourceClosed = true; |
|
1136 |
source = null; |
|
1137 |
closed = true; |
|
1138 |
} |
|
1139 |
||
1140 |
/** |
|
1141 |
* Returns the <code>IOException</code> last thrown by this |
|
1142 |
* <code>Scanner</code>'s underlying <code>Readable</code>. This method |
|
1143 |
* returns <code>null</code> if no such exception exists. |
|
1144 |
* |
|
1145 |
* @return the last exception thrown by this scanner's readable |
|
1146 |
*/ |
|
1147 |
public IOException ioException() { |
|
1148 |
return lastException; |
|
1149 |
} |
|
1150 |
||
1151 |
/** |
|
1152 |
* Returns the <code>Pattern</code> this <code>Scanner</code> is currently |
|
1153 |
* using to match delimiters. |
|
1154 |
* |
|
1155 |
* @return this scanner's delimiting pattern. |
|
1156 |
*/ |
|
1157 |
public Pattern delimiter() { |
|
1158 |
return delimPattern; |
|
1159 |
} |
|
1160 |
||
1161 |
/** |
|
1162 |
* Sets this scanner's delimiting pattern to the specified pattern. |
|
1163 |
* |
|
1164 |
* @param pattern A delimiting pattern |
|
1165 |
* @return this scanner |
|
1166 |
*/ |
|
1167 |
public Scanner useDelimiter(Pattern pattern) { |
|
1168 |
delimPattern = pattern; |
|
1169 |
return this; |
|
1170 |
} |
|
1171 |
||
1172 |
/** |
|
1173 |
* Sets this scanner's delimiting pattern to a pattern constructed from |
|
1174 |
* the specified <code>String</code>. |
|
1175 |
* |
|
1176 |
* <p> An invocation of this method of the form |
|
1177 |
* <tt>useDelimiter(pattern)</tt> behaves in exactly the same way as the |
|
1178 |
* invocation <tt>useDelimiter(Pattern.compile(pattern))</tt>. |
|
1179 |
* |
|
1180 |
* <p> Invoking the {@link #reset} method will set the scanner's delimiter |
|
1181 |
* to the <a href= "#default-delimiter">default</a>. |
|
1182 |
* |
|
1183 |
* @param pattern A string specifying a delimiting pattern |
|
1184 |
* @return this scanner |
|
1185 |
*/ |
|
1186 |
public Scanner useDelimiter(String pattern) { |
|
1187 |
delimPattern = patternCache.forName(pattern); |
|
1188 |
return this; |
|
1189 |
} |
|
1190 |
||
1191 |
/** |
|
1192 |
* Returns this scanner's locale. |
|
1193 |
* |
|
1194 |
* <p>A scanner's locale affects many elements of its default |
|
1195 |
* primitive matching regular expressions; see |
|
1196 |
* <a href= "#localized-numbers">localized numbers</a> above. |
|
1197 |
* |
|
1198 |
* @return this scanner's locale |
|
1199 |
*/ |
|
1200 |
public Locale locale() { |
|
1201 |
return this.locale; |
|
1202 |
} |
|
1203 |
||
1204 |
/** |
|
1205 |
* Sets this scanner's locale to the specified locale. |
|
1206 |
* |
|
1207 |
* <p>A scanner's locale affects many elements of its default |
|
1208 |
* primitive matching regular expressions; see |
|
1209 |
* <a href= "#localized-numbers">localized numbers</a> above. |
|
1210 |
* |
|
1211 |
* <p>Invoking the {@link #reset} method will set the scanner's locale to |
|
1212 |
* the <a href= "#initial-locale">initial locale</a>. |
|
1213 |
* |
|
1214 |
* @param locale A string specifying the locale to use |
|
1215 |
* @return this scanner |
|
1216 |
*/ |
|
1217 |
public Scanner useLocale(Locale locale) { |
|
1218 |
if (locale.equals(this.locale)) |
|
1219 |
return this; |
|
1220 |
||
1221 |
this.locale = locale; |
|
1222 |
DecimalFormat df = |
|
1223 |
(DecimalFormat)NumberFormat.getNumberInstance(locale); |
|
1224 |
DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(locale); |
|
1225 |
||
1226 |
// These must be literalized to avoid collision with regex |
|
1227 |
// metacharacters such as dot or parenthesis |
|
1228 |
groupSeparator = "\\" + dfs.getGroupingSeparator(); |
|
1229 |
decimalSeparator = "\\" + dfs.getDecimalSeparator(); |
|
1230 |
||
1231 |
// Quoting the nonzero length locale-specific things |
|
1232 |
// to avoid potential conflict with metacharacters |
|
1233 |
nanString = "\\Q" + dfs.getNaN() + "\\E"; |
|
1234 |
infinityString = "\\Q" + dfs.getInfinity() + "\\E"; |
|
1235 |
positivePrefix = df.getPositivePrefix(); |
|
1236 |
if (positivePrefix.length() > 0) |
|
1237 |
positivePrefix = "\\Q" + positivePrefix + "\\E"; |
|
1238 |
negativePrefix = df.getNegativePrefix(); |
|
1239 |
if (negativePrefix.length() > 0) |
|
1240 |
negativePrefix = "\\Q" + negativePrefix + "\\E"; |
|
1241 |
positiveSuffix = df.getPositiveSuffix(); |
|
1242 |
if (positiveSuffix.length() > 0) |
|
1243 |
positiveSuffix = "\\Q" + positiveSuffix + "\\E"; |
|
1244 |
negativeSuffix = df.getNegativeSuffix(); |
|
1245 |
if (negativeSuffix.length() > 0) |
|
1246 |
negativeSuffix = "\\Q" + negativeSuffix + "\\E"; |
|
1247 |
||
1248 |
// Force rebuilding and recompilation of locale dependent |
|
1249 |
// primitive patterns |
|
1250 |
integerPattern = null; |
|
1251 |
floatPattern = null; |
|
1252 |
||
1253 |
return this; |
|
1254 |
} |
|
1255 |
||
1256 |
/** |
|
1257 |
* Returns this scanner's default radix. |
|
1258 |
* |
|
1259 |
* <p>A scanner's radix affects elements of its default |
|
1260 |
* number matching regular expressions; see |
|
1261 |
* <a href= "#localized-numbers">localized numbers</a> above. |
|
1262 |
* |
|
1263 |
* @return the default radix of this scanner |
|
1264 |
*/ |
|
1265 |
public int radix() { |
|
1266 |
return this.defaultRadix; |
|
1267 |
} |
|
1268 |
||
1269 |
/** |
|
1270 |
* Sets this scanner's default radix to the specified radix. |
|
1271 |
* |
|
1272 |
* <p>A scanner's radix affects elements of its default |
|
1273 |
* number matching regular expressions; see |
|
1274 |
* <a href= "#localized-numbers">localized numbers</a> above. |
|
1275 |
* |
|
1276 |
* <p>If the radix is less than <code>Character.MIN_RADIX</code> |
|
1277 |
* or greater than <code>Character.MAX_RADIX</code>, then an |
|
1278 |
* <code>IllegalArgumentException</code> is thrown. |
|
1279 |
* |
|
1280 |
* <p>Invoking the {@link #reset} method will set the scanner's radix to |
|
1281 |
* <code>10</code>. |
|
1282 |
* |
|
1283 |
* @param radix The radix to use when scanning numbers |
|
1284 |
* @return this scanner |
|
1285 |
* @throws IllegalArgumentException if radix is out of range |
|
1286 |
*/ |
|
1287 |
public Scanner useRadix(int radix) { |
|
1288 |
if ((radix < Character.MIN_RADIX) || (radix > Character.MAX_RADIX)) |
|
1289 |
throw new IllegalArgumentException("radix:"+radix); |
|
1290 |
||
1291 |
if (this.defaultRadix == radix) |
|
1292 |
return this; |
|
1293 |
this.defaultRadix = radix; |
|
1294 |
// Force rebuilding and recompilation of radix dependent patterns |
|
1295 |
integerPattern = null; |
|
1296 |
return this; |
|
1297 |
} |
|
1298 |
||
1299 |
// The next operation should occur in the specified radix but |
|
1300 |
// the default is left untouched. |
|
1301 |
private void setRadix(int radix) { |
|
1302 |
if (this.radix != radix) { |
|
1303 |
// Force rebuilding and recompilation of radix dependent patterns |
|
1304 |
integerPattern = null; |
|
1305 |
this.radix = radix; |
|
1306 |
} |
|
1307 |
} |
|
1308 |
||
1309 |
/** |
|
1310 |
* Returns the match result of the last scanning operation performed |
|
1311 |
* by this scanner. This method throws <code>IllegalStateException</code> |
|
1312 |
* if no match has been performed, or if the last match was |
|
1313 |
* not successful. |
|
1314 |
* |
|
1315 |
* <p>The various <code>next</code>methods of <code>Scanner</code> |
|
1316 |
* make a match result available if they complete without throwing an |
|
1317 |
* exception. For instance, after an invocation of the {@link #nextInt} |
|
1318 |
* method that returned an int, this method returns a |
|
1319 |
* <code>MatchResult</code> for the search of the |
|
1320 |
* <a href="#Integer-regex"><i>Integer</i></a> regular expression |
|
1321 |
* defined above. Similarly the {@link #findInLine}, |
|
1322 |
* {@link #findWithinHorizon}, and {@link #skip} methods will make a |
|
1323 |
* match available if they succeed. |
|
1324 |
* |
|
1325 |
* @return a match result for the last match operation |
|
1326 |
* @throws IllegalStateException If no match result is available |
|
1327 |
*/ |
|
1328 |
public MatchResult match() { |
|
1329 |
if (!matchValid) |
|
1330 |
throw new IllegalStateException("No match result available"); |
|
1331 |
return matcher.toMatchResult(); |
|
1332 |
} |
|
1333 |
||
1334 |
/** |
|
1335 |
* <p>Returns the string representation of this <code>Scanner</code>. The |
|
1336 |
* string representation of a <code>Scanner</code> contains information |
|
1337 |
* that may be useful for debugging. The exact format is unspecified. |
|
1338 |
* |
|
1339 |
* @return The string representation of this scanner |
|
1340 |
*/ |
|
1341 |
public String toString() { |
|
1342 |
StringBuilder sb = new StringBuilder(); |
|
1343 |
sb.append("java.util.Scanner"); |
|
1344 |
sb.append("[delimiters=" + delimPattern + "]"); |
|
1345 |
sb.append("[position=" + position + "]"); |
|
1346 |
sb.append("[match valid=" + matchValid + "]"); |
|
1347 |
sb.append("[need input=" + needInput + "]"); |
|
1348 |
sb.append("[source closed=" + sourceClosed + "]"); |
|
1349 |
sb.append("[skipped=" + skipped + "]"); |
|
1350 |
sb.append("[group separator=" + groupSeparator + "]"); |
|
1351 |
sb.append("[decimal separator=" + decimalSeparator + "]"); |
|
1352 |
sb.append("[positive prefix=" + positivePrefix + "]"); |
|
1353 |
sb.append("[negative prefix=" + negativePrefix + "]"); |
|
1354 |
sb.append("[positive suffix=" + positiveSuffix + "]"); |
|
1355 |
sb.append("[negative suffix=" + negativeSuffix + "]"); |
|
1356 |
sb.append("[NaN string=" + nanString + "]"); |
|
1357 |
sb.append("[infinity string=" + infinityString + "]"); |
|
1358 |
return sb.toString(); |
|
1359 |
} |
|
1360 |
||
1361 |
/** |
|
1362 |
* Returns true if this scanner has another token in its input. |
|
1363 |
* This method may block while waiting for input to scan. |
|
1364 |
* The scanner does not advance past any input. |
|
1365 |
* |
|
1366 |
* @return true if and only if this scanner has another token |
|
1367 |
* @throws IllegalStateException if this scanner is closed |
|
1368 |
* @see java.util.Iterator |
|
1369 |
*/ |
|
1370 |
public boolean hasNext() { |
|
1371 |
ensureOpen(); |
|
1372 |
saveState(); |
|
1373 |
while (!sourceClosed) { |
|
1374 |
if (hasTokenInBuffer()) |
|
1375 |
return revertState(true); |
|
1376 |
readInput(); |
|
1377 |
} |
|
1378 |
boolean result = hasTokenInBuffer(); |
|
1379 |
return revertState(result); |
|
1380 |
} |
|
1381 |
||
1382 |
/** |
|
1383 |
* Finds and returns the next complete token from this scanner. |
|
1384 |
* A complete token is preceded and followed by input that matches |
|
1385 |
* the delimiter pattern. This method may block while waiting for input |
|
1386 |
* to scan, even if a previous invocation of {@link #hasNext} returned |
|
1387 |
* <code>true</code>. |
|
1388 |
* |
|
1389 |
* @return the next token |
|
1390 |
* @throws NoSuchElementException if no more tokens are available |
|
1391 |
* @throws IllegalStateException if this scanner is closed |
|
1392 |
* @see java.util.Iterator |
|
1393 |
*/ |
|
1394 |
public String next() { |
|
1395 |
ensureOpen(); |
|
1396 |
clearCaches(); |
|
1397 |
||
1398 |
while (true) { |
|
1399 |
String token = getCompleteTokenInBuffer(null); |
|
1400 |
if (token != null) { |
|
1401 |
matchValid = true; |
|
1402 |
skipped = false; |
|
1403 |
return token; |
|
1404 |
} |
|
1405 |
if (needInput) |
|
1406 |
readInput(); |
|
1407 |
else |
|
1408 |
throwFor(); |
|
1409 |
} |
|
1410 |
} |
|
1411 |
||
1412 |
/** |
|
1413 |
* The remove operation is not supported by this implementation of |
|
1414 |
* <code>Iterator</code>. |
|
1415 |
* |
|
1416 |
* @throws UnsupportedOperationException if this method is invoked. |
|
1417 |
* @see java.util.Iterator |
|
1418 |
*/ |
|
1419 |
public void remove() { |
|
1420 |
throw new UnsupportedOperationException(); |
|
1421 |
} |
|
1422 |
||
1423 |
/** |
|
1424 |
* Returns true if the next token matches the pattern constructed from the |
|
1425 |
* specified string. The scanner does not advance past any input. |
|
1426 |
* |
|
1427 |
* <p> An invocation of this method of the form <tt>hasNext(pattern)</tt> |
|
1428 |
* behaves in exactly the same way as the invocation |
|
1429 |
* <tt>hasNext(Pattern.compile(pattern))</tt>. |
|
1430 |
* |
|
1431 |
* @param pattern a string specifying the pattern to scan |
|
1432 |
* @return true if and only if this scanner has another token matching |
|
1433 |
* the specified pattern |
|
1434 |
* @throws IllegalStateException if this scanner is closed |
|
1435 |
*/ |
|
1436 |
public boolean hasNext(String pattern) { |
|
1437 |
return hasNext(patternCache.forName(pattern)); |
|
1438 |
} |
|
1439 |
||
1440 |
/** |
|
1441 |
* Returns the next token if it matches the pattern constructed from the |
|
1442 |
* specified string. If the match is successful, the scanner advances |
|
1443 |
* past the input that matched the pattern. |
|
1444 |
* |
|
1445 |
* <p> An invocation of this method of the form <tt>next(pattern)</tt> |
|
1446 |
* behaves in exactly the same way as the invocation |
|
1447 |
* <tt>next(Pattern.compile(pattern))</tt>. |
|
1448 |
* |
|
1449 |
* @param pattern a string specifying the pattern to scan |
|
1450 |
* @return the next token |
|
1451 |
* @throws NoSuchElementException if no such tokens are available |
|
1452 |
* @throws IllegalStateException if this scanner is closed |
|
1453 |
*/ |
|
1454 |
public String next(String pattern) { |
|
1455 |
return next(patternCache.forName(pattern)); |
|
1456 |
} |
|
1457 |
||
1458 |
/** |
|
1459 |
* Returns true if the next complete token matches the specified pattern. |
|
1460 |
* A complete token is prefixed and postfixed by input that matches |
|
1461 |
* the delimiter pattern. This method may block while waiting for input. |
|
1462 |
* The scanner does not advance past any input. |
|
1463 |
* |
|
1464 |
* @param pattern the pattern to scan for |
|
1465 |
* @return true if and only if this scanner has another token matching |
|
1466 |
* the specified pattern |
|
1467 |
* @throws IllegalStateException if this scanner is closed |
|
1468 |
*/ |
|
1469 |
public boolean hasNext(Pattern pattern) { |
|
1470 |
ensureOpen(); |
|
1471 |
if (pattern == null) |
|
1472 |
throw new NullPointerException(); |
|
1473 |
hasNextPattern = null; |
|
1474 |
saveState(); |
|
1475 |
||
1476 |
while (true) { |
|
1477 |
if (getCompleteTokenInBuffer(pattern) != null) { |
|
1478 |
matchValid = true; |
|
1479 |
cacheResult(); |
|
1480 |
return revertState(true); |
|
1481 |
} |
|
1482 |
if (needInput) |
|
1483 |
readInput(); |
|
1484 |
else |
|
1485 |
return revertState(false); |
|
1486 |
} |
|
1487 |
} |
|
1488 |
||
1489 |
/** |
|
1490 |
* Returns the next token if it matches the specified pattern. This |
|
1491 |
* method may block while waiting for input to scan, even if a previous |
|
1492 |
* invocation of {@link #hasNext(Pattern)} returned <code>true</code>. |
|
1493 |
* If the match is successful, the scanner advances past the input that |
|
1494 |
* matched the pattern. |
|
1495 |
* |
|
1496 |
* @param pattern the pattern to scan for |
|
1497 |
* @return the next token |
|
1498 |
* @throws NoSuchElementException if no more tokens are available |
|
1499 |
* @throws IllegalStateException if this scanner is closed |
|
1500 |
*/ |
|
1501 |
public String next(Pattern pattern) { |
|
1502 |
ensureOpen(); |
|
1503 |
if (pattern == null) |
|
1504 |
throw new NullPointerException(); |
|
1505 |
||
1506 |
// Did we already find this pattern? |
|
1507 |
if (hasNextPattern == pattern) |
|
1508 |
return getCachedResult(); |
|
1509 |
clearCaches(); |
|
1510 |
||
1511 |
// Search for the pattern |
|
1512 |
while (true) { |
|
1513 |
String token = getCompleteTokenInBuffer(pattern); |
|
1514 |
if (token != null) { |
|
1515 |
matchValid = true; |
|
1516 |
skipped = false; |
|
1517 |
return token; |
|
1518 |
} |
|
1519 |
if (needInput) |
|
1520 |
readInput(); |
|
1521 |
else |
|
1522 |
throwFor(); |
|
1523 |
} |
|
1524 |
} |
|
1525 |
||
1526 |
/** |
|
1527 |
* Returns true if there is another line in the input of this scanner. |
|
1528 |
* This method may block while waiting for input. The scanner does not |
|
1529 |
* advance past any input. |
|
1530 |
* |
|
1531 |
* @return true if and only if this scanner has another line of input |
|
1532 |
* @throws IllegalStateException if this scanner is closed |
|
1533 |
*/ |
|
1534 |
public boolean hasNextLine() { |
|
1535 |
saveState(); |
|
1536 |
||
1537 |
String result = findWithinHorizon(linePattern(), 0); |
|
1538 |
if (result != null) { |
|
1539 |
MatchResult mr = this.match(); |
|
1540 |
String lineSep = mr.group(1); |
|
1541 |
if (lineSep != null) { |
|
1542 |
result = result.substring(0, result.length() - |
|
1543 |
lineSep.length()); |
|
1544 |
cacheResult(result); |
|
1545 |
||
1546 |
} else { |
|
1547 |
cacheResult(); |
|
1548 |
} |
|
1549 |
} |
|
1550 |
revertState(); |
|
1551 |
return (result != null); |
|
1552 |
} |
|
1553 |
||
1554 |
/** |
|
1555 |
* Advances this scanner past the current line and returns the input |
|
1556 |
* that was skipped. |
|
1557 |
* |
|
1558 |
* This method returns the rest of the current line, excluding any line |
|
1559 |
* separator at the end. The position is set to the beginning of the next |
|
1560 |
* line. |
|
1561 |
* |
|
1562 |
* <p>Since this method continues to search through the input looking |
|
1563 |
* for a line separator, it may buffer all of the input searching for |
|
1564 |
* the line to skip if no line separators are present. |
|
1565 |
* |
|
1566 |
* @return the line that was skipped |
|
1567 |
* @throws NoSuchElementException if no line was found |
|
1568 |
* @throws IllegalStateException if this scanner is closed |
|
1569 |
*/ |
|
1570 |
public String nextLine() { |
|
1571 |
if (hasNextPattern == linePattern()) |
|
1572 |
return getCachedResult(); |
|
1573 |
clearCaches(); |
|
1574 |
||
1575 |
String result = findWithinHorizon(linePattern, 0); |
|
1576 |
if (result == null) |
|
1577 |
throw new NoSuchElementException("No line found"); |
|
1578 |
MatchResult mr = this.match(); |
|
1579 |
String lineSep = mr.group(1); |
|
1580 |
if (lineSep != null) |
|
1581 |
result = result.substring(0, result.length() - lineSep.length()); |
|
1582 |
if (result == null) |
|
1583 |
throw new NoSuchElementException(); |
|
1584 |
else |
|
1585 |
return result; |
|
1586 |
} |
|
1587 |
||
1588 |
// Public methods that ignore delimiters |
|
1589 |
||
1590 |
/** |
|
1591 |
* Attempts to find the next occurrence of a pattern constructed from the |
|
1592 |
* specified string, ignoring delimiters. |
|
1593 |
* |
|
1594 |
* <p>An invocation of this method of the form <tt>findInLine(pattern)</tt> |
|
1595 |
* behaves in exactly the same way as the invocation |
|
1596 |
* <tt>findInLine(Pattern.compile(pattern))</tt>. |
|
1597 |
* |
|
1598 |
* @param pattern a string specifying the pattern to search for |
|
1599 |
* @return the text that matched the specified pattern |
|
1600 |
* @throws IllegalStateException if this scanner is closed |
|
1601 |
*/ |
|
1602 |
public String findInLine(String pattern) { |
|
1603 |
return findInLine(patternCache.forName(pattern)); |
|
1604 |
} |
|
1605 |
||
1606 |
/** |
|
1607 |
* Attempts to find the next occurrence of the specified pattern ignoring |
|
1608 |
* delimiters. If the pattern is found before the next line separator, the |
|
1609 |
* scanner advances past the input that matched and returns the string that |
|
1610 |
* matched the pattern. |
|
1611 |
* If no such pattern is detected in the input up to the next line |
|
1612 |
* separator, then <code>null</code> is returned and the scanner's |
|
1613 |
* position is unchanged. This method may block waiting for input that |
|
1614 |
* matches the pattern. |
|
1615 |
* |
|
1616 |
* <p>Since this method continues to search through the input looking |
|
1617 |
* for the specified pattern, it may buffer all of the input searching for |
|
1618 |
* the desired token if no line separators are present. |
|
1619 |
* |
|
1620 |
* @param pattern the pattern to scan for |
|
1621 |
* @return the text that matched the specified pattern |
|
1622 |
* @throws IllegalStateException if this scanner is closed |
|
1623 |
*/ |
|
1624 |
public String findInLine(Pattern pattern) { |
|
1625 |
ensureOpen(); |
|
1626 |
if (pattern == null) |
|
1627 |
throw new NullPointerException(); |
|
1628 |
clearCaches(); |
|
1629 |
// Expand buffer to include the next newline or end of input |
|
1630 |
int endPosition = 0; |
|
1631 |
saveState(); |
|
1632 |
while (true) { |
|
1633 |
String token = findPatternInBuffer(separatorPattern(), 0); |
|
1634 |
if (token != null) { |
|
1635 |
endPosition = matcher.start(); |
|
1636 |
break; // up to next newline |
|
1637 |
} |
|
1638 |
if (needInput) { |
|
1639 |
readInput(); |
|
1640 |
} else { |
|
1641 |
endPosition = buf.limit(); |
|
1642 |
break; // up to end of input |
|
1643 |
} |
|
1644 |
} |
|
1645 |
revertState(); |
|
1646 |
int horizonForLine = endPosition - position; |
|
1647 |
// If there is nothing between the current pos and the next |
|
1648 |
// newline simply return null, invoking findWithinHorizon |
|
1649 |
// with "horizon=0" will scan beyond the line bound. |
|
1650 |
if (horizonForLine == 0) |
|
1651 |
return null; |
|
1652 |
// Search for the pattern |
|
1653 |
return findWithinHorizon(pattern, horizonForLine); |
|
1654 |
} |
|
1655 |
||
1656 |
/** |
|
1657 |
* Attempts to find the next occurrence of a pattern constructed from the |
|
1658 |
* specified string, ignoring delimiters. |
|
1659 |
* |
|
1660 |
* <p>An invocation of this method of the form |
|
1661 |
* <tt>findWithinHorizon(pattern)</tt> behaves in exactly the same way as |
|
1662 |
* the invocation |
|
1663 |
* <tt>findWithinHorizon(Pattern.compile(pattern, horizon))</tt>. |
|
1664 |
* |
|
1665 |
* @param pattern a string specifying the pattern to search for |
|
1666 |
* @return the text that matched the specified pattern |
|
1667 |
* @throws IllegalStateException if this scanner is closed |
|
1668 |
* @throws IllegalArgumentException if horizon is negative |
|
1669 |
*/ |
|
1670 |
public String findWithinHorizon(String pattern, int horizon) { |
|
1671 |
return findWithinHorizon(patternCache.forName(pattern), horizon); |
|
1672 |
} |
|
1673 |
||
1674 |
/** |
|
1675 |
* Attempts to find the next occurrence of the specified pattern. |
|
1676 |
* |
|
1677 |
* <p>This method searches through the input up to the specified |
|
1678 |
* search horizon, ignoring delimiters. If the pattern is found the |
|
1679 |
* scanner advances past the input that matched and returns the string |
|
1680 |
* that matched the pattern. If no such pattern is detected then the |
|
1681 |
* null is returned and the scanner's position remains unchanged. This |
|
1682 |
* method may block waiting for input that matches the pattern. |
|
1683 |
* |
|
1684 |
* <p>A scanner will never search more than <code>horizon</code> code |
|
1685 |
* points beyond its current position. Note that a match may be clipped |
|
1686 |
* by the horizon; that is, an arbitrary match result may have been |
|
1687 |
* different if the horizon had been larger. The scanner treats the |
|
1688 |
* horizon as a transparent, non-anchoring bound (see {@link |
|
1689 |
* Matcher#useTransparentBounds} and {@link Matcher#useAnchoringBounds}). |
|
1690 |
* |
|
1691 |
* <p>If horizon is <code>0</code>, then the horizon is ignored and |
|
1692 |
* this method continues to search through the input looking for the |
|
1693 |
* specified pattern without bound. In this case it may buffer all of |
|
1694 |
* the input searching for the pattern. |
|
1695 |
* |
|
1696 |
* <p>If horizon is negative, then an IllegalArgumentException is |
|
1697 |
* thrown. |
|
1698 |
* |
|
1699 |
* @param pattern the pattern to scan for |
|
1700 |
* @return the text that matched the specified pattern |
|
1701 |
* @throws IllegalStateException if this scanner is closed |
|
1702 |
* @throws IllegalArgumentException if horizon is negative |
|
1703 |
*/ |
|
1704 |
public String findWithinHorizon(Pattern pattern, int horizon) { |
|
1705 |
ensureOpen(); |
|
1706 |
if (pattern == null) |
|
1707 |
throw new NullPointerException(); |
|
1708 |
if (horizon < 0) |
|
1709 |
throw new IllegalArgumentException("horizon < 0"); |
|
1710 |
clearCaches(); |
|
1711 |
||
1712 |
// Search for the pattern |
|
1713 |
while (true) { |
|
1714 |
String token = findPatternInBuffer(pattern, horizon); |
|
1715 |
if (token != null) { |
|
1716 |
matchValid = true; |
|
1717 |
return token; |
|
1718 |
} |
|
1719 |
if (needInput) |
|
1720 |
readInput(); |
|
1721 |
else |
|
1722 |
break; // up to end of input |
|
1723 |
} |
|
1724 |
return null; |
|
1725 |
} |
|
1726 |
||
1727 |
/** |
|
1728 |
* Skips input that matches the specified pattern, ignoring delimiters. |
|
1729 |
* This method will skip input if an anchored match of the specified |
|
1730 |
* pattern succeeds. |
|
1731 |
* |
|
1732 |
* <p>If a match to the specified pattern is not found at the |
|
1733 |
* current position, then no input is skipped and a |
|
1734 |
* <tt>NoSuchElementException</tt> is thrown. |
|
1735 |
* |
|
1736 |
* <p>Since this method seeks to match the specified pattern starting at |
|
1737 |
* the scanner's current position, patterns that can match a lot of |
|
1738 |
* input (".*", for example) may cause the scanner to buffer a large |
|
1739 |
* amount of input. |
|
1740 |
* |
|
1741 |
* <p>Note that it is possible to skip something without risking a |
|
1742 |
* <code>NoSuchElementException</code> by using a pattern that can |
|
1743 |
* match nothing, e.g., <code>sc.skip("[ \t]*")</code>. |
|
1744 |
* |
|
1745 |
* @param pattern a string specifying the pattern to skip over |
|
1746 |
* @return this scanner |
|
1747 |
* @throws NoSuchElementException if the specified pattern is not found |
|
1748 |
* @throws IllegalStateException if this scanner is closed |
|
1749 |
*/ |
|
1750 |
public Scanner skip(Pattern pattern) { |
|
1751 |
ensureOpen(); |
|
1752 |
if (pattern == null) |
|
1753 |
throw new NullPointerException(); |
|
1754 |
clearCaches(); |
|
1755 |
||
1756 |
// Search for the pattern |
|
1757 |
while (true) { |
|
1758 |
String token = matchPatternInBuffer(pattern); |
|
1759 |
if (token != null) { |
|
1760 |
matchValid = true; |
|
1761 |
position = matcher.end(); |
|
1762 |
return this; |
|
1763 |
} |
|
1764 |
if (needInput) |
|
1765 |
readInput(); |
|
1766 |
else |
|
1767 |
throw new NoSuchElementException(); |
|
1768 |
} |
|
1769 |
} |
|
1770 |
||
1771 |
/** |
|
1772 |
* Skips input that matches a pattern constructed from the specified |
|
1773 |
* string. |
|
1774 |
* |
|
1775 |
* <p> An invocation of this method of the form <tt>skip(pattern)</tt> |
|
1776 |
* behaves in exactly the same way as the invocation |
|
1777 |
* <tt>skip(Pattern.compile(pattern))</tt>. |
|
1778 |
* |
|
1779 |
* @param pattern a string specifying the pattern to skip over |
|
1780 |
* @return this scanner |
|
1781 |
* @throws IllegalStateException if this scanner is closed |
|
1782 |
*/ |
|
1783 |
public Scanner skip(String pattern) { |
|
1784 |
return skip(patternCache.forName(pattern)); |
|
1785 |
} |
|
1786 |
||
1787 |
// Convenience methods for scanning primitives |
|
1788 |
||
1789 |
/** |
|
1790 |
* Returns true if the next token in this scanner's input can be |
|
1791 |
* interpreted as a boolean value using a case insensitive pattern |
|
1792 |
* created from the string "true|false". The scanner does not |
|
1793 |
* advance past the input that matched. |
|
1794 |
* |
|
1795 |
* @return true if and only if this scanner's next token is a valid |
|
1796 |
* boolean value |
|
1797 |
* @throws IllegalStateException if this scanner is closed |
|
1798 |
*/ |
|
1799 |
public boolean hasNextBoolean() { |
|
1800 |
return hasNext(boolPattern()); |
|
1801 |
} |
|
1802 |
||
1803 |
/** |
|
1804 |
* Scans the next token of the input into a boolean value and returns |
|
1805 |
* that value. This method will throw <code>InputMismatchException</code> |
|
1806 |
* if the next token cannot be translated into a valid boolean value. |
|
1807 |
* If the match is successful, the scanner advances past the input that |
|
1808 |
* matched. |
|
1809 |
* |
|
1810 |
* @return the boolean scanned from the input |
|
1811 |
* @throws InputMismatchException if the next token is not a valid boolean |
|
1812 |
* @throws NoSuchElementException if input is exhausted |
|
1813 |
* @throws IllegalStateException if this scanner is closed |
|
1814 |
*/ |
|
1815 |
public boolean nextBoolean() { |
|
1816 |
clearCaches(); |
|
1817 |
return Boolean.parseBoolean(next(boolPattern())); |
|
1818 |
} |
|
1819 |
||
1820 |
/** |
|
1821 |
* Returns true if the next token in this scanner's input can be |
|
1822 |
* interpreted as a byte value in the default radix using the |
|
1823 |
* {@link #nextByte} method. The scanner does not advance past any input. |
|
1824 |
* |
|
1825 |
* @return true if and only if this scanner's next token is a valid |
|
1826 |
* byte value |
|
1827 |
* @throws IllegalStateException if this scanner is closed |
|
1828 |
*/ |
|
1829 |
public boolean hasNextByte() { |
|
1830 |
return hasNextByte(defaultRadix); |
|
1831 |
} |
|
1832 |
||
1833 |
/** |
|
1834 |
* Returns true if the next token in this scanner's input can be |
|
1835 |
* interpreted as a byte value in the specified radix using the |
|
1836 |
* {@link #nextByte} method. The scanner does not advance past any input. |
|
1837 |
* |
|
1838 |
* @param radix the radix used to interpret the token as a byte value |
|
1839 |
* @return true if and only if this scanner's next token is a valid |
|
1840 |
* byte value |
|
1841 |
* @throws IllegalStateException if this scanner is closed |
|
1842 |
*/ |
|
1843 |
public boolean hasNextByte(int radix) { |
|
1844 |
setRadix(radix); |
|
1845 |
boolean result = hasNext(integerPattern()); |
|
1846 |
if (result) { // Cache it |
|
1847 |
try { |
|
1848 |
String s = (matcher.group(SIMPLE_GROUP_INDEX) == null) ? |
|
1849 |
processIntegerToken(hasNextResult) : |
|
1850 |
hasNextResult; |
|
1851 |
typeCache = Byte.parseByte(s, radix); |
|
1852 |
} catch (NumberFormatException nfe) { |
|
1853 |
result = false; |
|
1854 |
} |
|
1855 |
} |
|
1856 |
return result; |
|
1857 |
} |
|
1858 |
||
1859 |
/** |
|
1860 |
* Scans the next token of the input as a <tt>byte</tt>. |
|
1861 |
* |
|
1862 |
* <p> An invocation of this method of the form |
|
1863 |
* <tt>nextByte()</tt> behaves in exactly the same way as the |
|
1864 |
* invocation <tt>nextByte(radix)</tt>, where <code>radix</code> |
|
1865 |
* is the default radix of this scanner. |
|
1866 |
* |
|
1867 |
* @return the <tt>byte</tt> scanned from the input |
|
1868 |
* @throws InputMismatchException |
|
1869 |
* if the next token does not match the <i>Integer</i> |
|
1870 |
* regular expression, or is out of range |
|
1871 |
* @throws NoSuchElementException if input is exhausted |
|
1872 |
* @throws IllegalStateException if this scanner is closed |
|
1873 |
*/ |
|
1874 |
public byte nextByte() { |
|
1875 |
return nextByte(defaultRadix); |
|
1876 |
} |
|
1877 |
||
1878 |
/** |
|
1879 |
* Scans the next token of the input as a <tt>byte</tt>. |
|
1880 |
* This method will throw <code>InputMismatchException</code> |
|
1881 |
* if the next token cannot be translated into a valid byte value as |
|
1882 |
* described below. If the translation is successful, the scanner advances |
|
1883 |
* past the input that matched. |
|
1884 |
* |
|
1885 |
* <p> If the next token matches the <a |
|
1886 |
* href="#Integer-regex"><i>Integer</i></a> regular expression defined |
|
1887 |
* above then the token is converted into a <tt>byte</tt> value as if by |
|
1888 |
* removing all locale specific prefixes, group separators, and locale |
|
1889 |
* specific suffixes, then mapping non-ASCII digits into ASCII |
|
1890 |
* digits via {@link Character#digit Character.digit}, prepending a |
|
1891 |
* negative sign (-) if the locale specific negative prefixes and suffixes |
|
1892 |
* were present, and passing the resulting string to |
|
1893 |
* {@link Byte#parseByte(String, int) Byte.parseByte} with the |
|
1894 |
* specified radix. |
|
1895 |
* |
|
1896 |
* @param radix the radix used to interpret the token as a byte value |
|
1897 |
* @return the <tt>byte</tt> scanned from the input |
|
1898 |
* @throws InputMismatchException |
|
1899 |
* if the next token does not match the <i>Integer</i> |
|
1900 |
* regular expression, or is out of range |
|
1901 |
* @throws NoSuchElementException if input is exhausted |
|
1902 |
* @throws IllegalStateException if this scanner is closed |
|
1903 |
*/ |
|
1904 |
public byte nextByte(int radix) { |
|
1905 |
// Check cached result |
|
1906 |
if ((typeCache != null) && (typeCache instanceof Byte) |
|
1907 |
&& this.radix == radix) { |
|
1908 |
byte val = ((Byte)typeCache).byteValue(); |
|
1909 |
useTypeCache(); |
|
1910 |
return val; |
|
1911 |
} |
|
1912 |
setRadix(radix); |
|
1913 |
clearCaches(); |
|
1914 |
// Search for next byte |
|
1915 |
try { |
|
1916 |
String s = next(integerPattern()); |
|
1917 |
if (matcher.group(SIMPLE_GROUP_INDEX) == null) |
|
1918 |
s = processIntegerToken(s); |
|
1919 |
return Byte.parseByte(s, radix); |
|
1920 |
} catch (NumberFormatException nfe) { |
|
1921 |
position = matcher.start(); // don't skip bad token |
|
1922 |
throw new InputMismatchException(nfe.getMessage()); |
|
1923 |
} |
|
1924 |
} |
|
1925 |
||
1926 |
/** |
|
1927 |
* Returns true if the next token in this scanner's input can be |
|
1928 |
* interpreted as a short value in the default radix using the |
|
1929 |
* {@link #nextShort} method. The scanner does not advance past any input. |
|
1930 |
* |
|
1931 |
* @return true if and only if this scanner's next token is a valid |
|
1932 |
* short value in the default radix |
|
1933 |
* @throws IllegalStateException if this scanner is closed |
|
1934 |
*/ |
|
1935 |
public boolean hasNextShort() { |
|
1936 |
return hasNextShort(defaultRadix); |
|
1937 |
} |
|
1938 |
||
1939 |
/** |
|
1940 |
* Returns true if the next token in this scanner's input can be |
|
1941 |
* interpreted as a short value in the specified radix using the |
|
1942 |
* {@link #nextShort} method. The scanner does not advance past any input. |
|
1943 |
* |
|
1944 |
* @param radix the radix used to interpret the token as a short value |
|
1945 |
* @return true if and only if this scanner's next token is a valid |
|
1946 |
* short value in the specified radix |
|
1947 |
* @throws IllegalStateException if this scanner is closed |
|
1948 |
*/ |
|
1949 |
public boolean hasNextShort(int radix) { |
|
1950 |
setRadix(radix); |
|
1951 |
boolean result = hasNext(integerPattern()); |
|
1952 |
if (result) { // Cache it |
|
1953 |
try { |
|
1954 |
String s = (matcher.group(SIMPLE_GROUP_INDEX) == null) ? |
|
1955 |
processIntegerToken(hasNextResult) : |
|
1956 |
hasNextResult; |
|
1957 |
typeCache = Short.parseShort(s, radix); |
|
1958 |
} catch (NumberFormatException nfe) { |
|
1959 |
result = false; |
|
1960 |
} |
|
1961 |
} |
|
1962 |
return result; |
|
1963 |
} |
|
1964 |
||
1965 |
/** |
|
1966 |
* Scans the next token of the input as a <tt>short</tt>. |
|
1967 |
* |
|
1968 |
* <p> An invocation of this method of the form |
|
1969 |
* <tt>nextShort()</tt> behaves in exactly the same way as the |
|
1970 |
* invocation <tt>nextShort(radix)</tt>, where <code>radix</code> |
|
1971 |
* is the default radix of this scanner. |
|
1972 |
* |
|
1973 |
* @return the <tt>short</tt> scanned from the input |
|
1974 |
* @throws InputMismatchException |
|
1975 |
* if the next token does not match the <i>Integer</i> |
|
1976 |
* regular expression, or is out of range |
|
1977 |
* @throws NoSuchElementException if input is exhausted |
|
1978 |
* @throws IllegalStateException if this scanner is closed |
|
1979 |
*/ |
|
1980 |
public short nextShort() { |
|
1981 |
return nextShort(defaultRadix); |
|
1982 |
} |
|
1983 |
||
1984 |
/** |
|
1985 |
* Scans the next token of the input as a <tt>short</tt>. |
|
1986 |
* This method will throw <code>InputMismatchException</code> |
|
1987 |
* if the next token cannot be translated into a valid short value as |
|
1988 |
* described below. If the translation is successful, the scanner advances |
|
1989 |
* past the input that matched. |
|
1990 |
* |
|
1991 |
* <p> If the next token matches the <a |
|
1992 |
* href="#Integer-regex"><i>Integer</i></a> regular expression defined |
|
1993 |
* above then the token is converted into a <tt>short</tt> value as if by |
|
1994 |
* removing all locale specific prefixes, group separators, and locale |
|
1995 |
* specific suffixes, then mapping non-ASCII digits into ASCII |
|
1996 |
* digits via {@link Character#digit Character.digit}, prepending a |
|
1997 |
* negative sign (-) if the locale specific negative prefixes and suffixes |
|
1998 |
* were present, and passing the resulting string to |
|
1999 |
* {@link Short#parseShort(String, int) Short.parseShort} with the |
|
2000 |
* specified radix. |
|
2001 |
* |
|
2002 |
* @param radix the radix used to interpret the token as a short value |
|
2003 |
* @return the <tt>short</tt> scanned from the input |
|
2004 |
* @throws InputMismatchException |
|
2005 |
* if the next token does not match the <i>Integer</i> |
|
2006 |
* regular expression, or is out of range |
|
2007 |
* @throws NoSuchElementException if input is exhausted |
|
2008 |
* @throws IllegalStateException if this scanner is closed |
|
2009 |
*/ |
|
2010 |
public short nextShort(int radix) { |
|
2011 |
// Check cached result |
|
2012 |
if ((typeCache != null) && (typeCache instanceof Short) |
|
2013 |
&& this.radix == radix) { |
|
2014 |
short val = ((Short)typeCache).shortValue(); |
|
2015 |
useTypeCache(); |
|
2016 |
return val; |
|
2017 |
} |
|
2018 |
setRadix(radix); |
|
2019 |
clearCaches(); |
|
2020 |
// Search for next short |
|
2021 |
try { |
|
2022 |
String s = next(integerPattern()); |
|
2023 |
if (matcher.group(SIMPLE_GROUP_INDEX) == null) |
|
2024 |
s = processIntegerToken(s); |
|
2025 |
return Short.parseShort(s, radix); |
|
2026 |
} catch (NumberFormatException nfe) { |
|
2027 |
position = matcher.start(); // don't skip bad token |
|
2028 |
throw new InputMismatchException(nfe.getMessage()); |
|
2029 |
} |
|
2030 |
} |
|
2031 |
||
2032 |
/** |
|
2033 |
* Returns true if the next token in this scanner's input can be |
|
2034 |
* interpreted as an int value in the default radix using the |
|
2035 |
* {@link #nextInt} method. The scanner does not advance past any input. |
|
2036 |
* |
|
2037 |
* @return true if and only if this scanner's next token is a valid |
|
2038 |
* int value |
|
2039 |
* @throws IllegalStateException if this scanner is closed |
|
2040 |
*/ |
|
2041 |
public boolean hasNextInt() { |
|
2042 |
return hasNextInt(defaultRadix); |
|
2043 |
} |
|
2044 |
||
2045 |
/** |
|
2046 |
* Returns true if the next token in this scanner's input can be |
|
2047 |
* interpreted as an int value in the specified radix using the |
|
2048 |
* {@link #nextInt} method. The scanner does not advance past any input. |
|
2049 |
* |
|
2050 |
* @param radix the radix used to interpret the token as an int value |
|
2051 |
* @return true if and only if this scanner's next token is a valid |
|
2052 |
* int value |
|
2053 |
* @throws IllegalStateException if this scanner is closed |
|
2054 |
*/ |
|
2055 |
public boolean hasNextInt(int radix) { |
|
2056 |
setRadix(radix); |
|
2057 |
boolean result = hasNext(integerPattern()); |
|
2058 |
if (result) { // Cache it |
|
2059 |
try { |
|
2060 |
String s = (matcher.group(SIMPLE_GROUP_INDEX) == null) ? |
|
2061 |
processIntegerToken(hasNextResult) : |
|
2062 |
hasNextResult; |
|
2063 |
typeCache = Integer.parseInt(s, radix); |
|
2064 |
} catch (NumberFormatException nfe) { |
|
2065 |
result = false; |
|
2066 |
} |
|
2067 |
} |
|
2068 |
return result; |
|
2069 |
} |
|
2070 |
||
2071 |
/** |
|
2072 |
* The integer token must be stripped of prefixes, group separators, |
|
2073 |
* and suffixes, non ascii digits must be converted into ascii digits |
|
2074 |
* before parse will accept it. |
|
2075 |
*/ |
|
2076 |
private String processIntegerToken(String token) { |
|
2077 |
String result = token.replaceAll(""+groupSeparator, ""); |
|
2078 |
boolean isNegative = false; |
|
2079 |
int preLen = negativePrefix.length(); |
|
2080 |
if ((preLen > 0) && result.startsWith(negativePrefix)) { |
|
2081 |
isNegative = true; |
|
2082 |
result = result.substring(preLen); |
|
2083 |
} |
|
2084 |
int sufLen = negativeSuffix.length(); |
|
2085 |
if ((sufLen > 0) && result.endsWith(negativeSuffix)) { |
|
2086 |
isNegative = true; |
|
2087 |
result = result.substring(result.length() - sufLen, |
|
2088 |
result.length()); |
|
2089 |
} |
|
2090 |
if (isNegative) |
|
2091 |
result = "-" + result; |
|
2092 |
return result; |
|
2093 |
} |
|
2094 |
||
2095 |
/** |
|
2096 |
* Scans the next token of the input as an <tt>int</tt>. |
|
2097 |
* |
|
2098 |
* <p> An invocation of this method of the form |
|
2099 |
* <tt>nextInt()</tt> behaves in exactly the same way as the |
|
2100 |
* invocation <tt>nextInt(radix)</tt>, where <code>radix</code> |
|
2101 |
* is the default radix of this scanner. |
|
2102 |
* |
|
2103 |
* @return the <tt>int</tt> scanned from the input |
|
2104 |
* @throws InputMismatchException |
|
2105 |
* if the next token does not match the <i>Integer</i> |
|
2106 |
* regular expression, or is out of range |
|
2107 |
* @throws NoSuchElementException if input is exhausted |
|
2108 |
* @throws IllegalStateException if this scanner is closed |
|
2109 |
*/ |
|
2110 |
public int nextInt() { |
|
2111 |
return nextInt(defaultRadix); |
|
2112 |
} |
|
2113 |
||
2114 |
/** |
|
2115 |
* Scans the next token of the input as an <tt>int</tt>. |
|
2116 |
* This method will throw <code>InputMismatchException</code> |
|
2117 |
* if the next token cannot be translated into a valid int value as |
|
2118 |
* described below. If the translation is successful, the scanner advances |
|
2119 |
* past the input that matched. |
|
2120 |
* |
|
2121 |
* <p> If the next token matches the <a |
|
2122 |
* href="#Integer-regex"><i>Integer</i></a> regular expression defined |
|
2123 |
* above then the token is converted into an <tt>int</tt> value as if by |
|
2124 |
* removing all locale specific prefixes, group separators, and locale |
|
2125 |
* specific suffixes, then mapping non-ASCII digits into ASCII |
|
2126 |
* digits via {@link Character#digit Character.digit}, prepending a |
|
2127 |
* negative sign (-) if the locale specific negative prefixes and suffixes |
|
2128 |
* were present, and passing the resulting string to |
|
2129 |
* {@link Integer#parseInt(String, int) Integer.parseInt} with the |
|
2130 |
* specified radix. |
|
2131 |
* |
|
2132 |
* @param radix the radix used to interpret the token as an int value |
|
2133 |
* @return the <tt>int</tt> scanned from the input |
|
2134 |
* @throws InputMismatchException |
|
2135 |
* if the next token does not match the <i>Integer</i> |
|
2136 |
* regular expression, or is out of range |
|
2137 |
* @throws NoSuchElementException if input is exhausted |
|
2138 |
* @throws IllegalStateException if this scanner is closed |
|
2139 |
*/ |
|
2140 |
public int nextInt(int radix) { |
|
2141 |
// Check cached result |
|
2142 |
if ((typeCache != null) && (typeCache instanceof Integer) |
|
2143 |
&& this.radix == radix) { |
|
2144 |
int val = ((Integer)typeCache).intValue(); |
|
2145 |
useTypeCache(); |
|
2146 |
return val; |
|
2147 |
} |
|
2148 |
setRadix(radix); |
|
2149 |
clearCaches(); |
|
2150 |
// Search for next int |
|
2151 |
try { |
|
2152 |
String s = next(integerPattern()); |
|
2153 |
if (matcher.group(SIMPLE_GROUP_INDEX) == null) |
|
2154 |
s = processIntegerToken(s); |
|
2155 |
return Integer.parseInt(s, radix); |
|
2156 |
} catch (NumberFormatException nfe) { |
|
2157 |
position = matcher.start(); // don't skip bad token |
|
2158 |
throw new InputMismatchException(nfe.getMessage()); |
|
2159 |
} |
|
2160 |
} |
|
2161 |
||
2162 |
/** |
|
2163 |
* Returns true if the next token in this scanner's input can be |
|
2164 |
* interpreted as a long value in the default radix using the |
|
2165 |
* {@link #nextLong} method. The scanner does not advance past any input. |
|
2166 |
* |
|
2167 |
* @return true if and only if this scanner's next token is a valid |
|
2168 |
* long value |
|
2169 |
* @throws IllegalStateException if this scanner is closed |
|
2170 |
*/ |
|
2171 |
public boolean hasNextLong() { |
|
2172 |
return hasNextLong(defaultRadix); |
|
2173 |
} |
|
2174 |
||
2175 |
/** |
|
2176 |
* Returns true if the next token in this scanner's input can be |
|
2177 |
* interpreted as a long value in the specified radix using the |
|
2178 |
* {@link #nextLong} method. The scanner does not advance past any input. |
|
2179 |
* |
|
2180 |
* @param radix the radix used to interpret the token as a long value |
|
2181 |
* @return true if and only if this scanner's next token is a valid |
|
2182 |
* long value |
|
2183 |
* @throws IllegalStateException if this scanner is closed |
|
2184 |
*/ |
|
2185 |
public boolean hasNextLong(int radix) { |
|
2186 |
setRadix(radix); |
|
2187 |
boolean result = hasNext(integerPattern()); |
|
2188 |
if (result) { // Cache it |
|
2189 |
try { |
|
2190 |
String s = (matcher.group(SIMPLE_GROUP_INDEX) == null) ? |
|
2191 |
processIntegerToken(hasNextResult) : |
|
2192 |
hasNextResult; |
|
2193 |
typeCache = Long.parseLong(s, radix); |
|
2194 |
} catch (NumberFormatException nfe) { |
|
2195 |
result = false; |
|
2196 |
} |
|
2197 |
} |
|
2198 |
return result; |
|
2199 |
} |
|
2200 |
||
2201 |
/** |
|
2202 |
* Scans the next token of the input as a <tt>long</tt>. |
|
2203 |
* |
|
2204 |
* <p> An invocation of this method of the form |
|
2205 |
* <tt>nextLong()</tt> behaves in exactly the same way as the |
|
2206 |
* invocation <tt>nextLong(radix)</tt>, where <code>radix</code> |
|
2207 |
* is the default radix of this scanner. |
|
2208 |
* |
|
2209 |
* @return the <tt>long</tt> scanned from the input |
|
2210 |
* @throws InputMismatchException |
|
2211 |
* if the next token does not match the <i>Integer</i> |
|
2212 |
* regular expression, or is out of range |
|
2213 |
* @throws NoSuchElementException if input is exhausted |
|
2214 |
* @throws IllegalStateException if this scanner is closed |
|
2215 |
*/ |
|
2216 |
public long nextLong() { |
|
2217 |
return nextLong(defaultRadix); |
|
2218 |
} |
|
2219 |
||
2220 |
/** |
|
2221 |
* Scans the next token of the input as a <tt>long</tt>. |
|
2222 |
* This method will throw <code>InputMismatchException</code> |
|
2223 |
* if the next token cannot be translated into a valid long value as |
|
2224 |
* described below. If the translation is successful, the scanner advances |
|
2225 |
* past the input that matched. |
|
2226 |
* |
|
2227 |
* <p> If the next token matches the <a |
|
2228 |
* href="#Integer-regex"><i>Integer</i></a> regular expression defined |
|
2229 |
* above then the token is converted into a <tt>long</tt> value as if by |
|
2230 |
* removing all locale specific prefixes, group separators, and locale |
|
2231 |
* specific suffixes, then mapping non-ASCII digits into ASCII |
|
2232 |
* digits via {@link Character#digit Character.digit}, prepending a |
|
2233 |
* negative sign (-) if the locale specific negative prefixes and suffixes |
|
2234 |
* were present, and passing the resulting string to |
|
2235 |
* {@link Long#parseLong(String, int) Long.parseLong} with the |
|
2236 |
* specified radix. |
|
2237 |
* |
|
2238 |
* @param radix the radix used to interpret the token as an int value |
|
2239 |
* @return the <tt>long</tt> scanned from the input |
|
2240 |
* @throws InputMismatchException |
|
2241 |
* if the next token does not match the <i>Integer</i> |
|
2242 |
* regular expression, or is out of range |
|
2243 |
* @throws NoSuchElementException if input is exhausted |
|
2244 |
* @throws IllegalStateException if this scanner is closed |
|
2245 |
*/ |
|
2246 |
public long nextLong(int radix) { |
|
2247 |
// Check cached result |
|
2248 |
if ((typeCache != null) && (typeCache instanceof Long) |
|
2249 |
&& this.radix == radix) { |
|
2250 |
long val = ((Long)typeCache).longValue(); |
|
2251 |
useTypeCache(); |
|
2252 |
return val; |
|
2253 |
} |
|
2254 |
setRadix(radix); |
|
2255 |
clearCaches(); |
|
2256 |
try { |
|
2257 |
String s = next(integerPattern()); |
|
2258 |
if (matcher.group(SIMPLE_GROUP_INDEX) == null) |
|
2259 |
s = processIntegerToken(s); |
|
2260 |
return Long.parseLong(s, radix); |
|
2261 |
} catch (NumberFormatException nfe) { |
|
2262 |
position = matcher.start(); // don't skip bad token |
|
2263 |
throw new InputMismatchException(nfe.getMessage()); |
|
2264 |
} |
|
2265 |
} |
|
2266 |
||
2267 |
/** |
|
2268 |
* The float token must be stripped of prefixes, group separators, |
|
2269 |
* and suffixes, non ascii digits must be converted into ascii digits |
|
2270 |
* before parseFloat will accept it. |
|
2271 |
* |
|
2272 |
* If there are non-ascii digits in the token these digits must |
|
2273 |
* be processed before the token is passed to parseFloat. |
|
2274 |
*/ |
|
2275 |
private String processFloatToken(String token) { |
|
2276 |
String result = token.replaceAll(groupSeparator, ""); |
|
2277 |
if (!decimalSeparator.equals("\\.")) |
|
2278 |
result = result.replaceAll(decimalSeparator, "."); |
|
2279 |
boolean isNegative = false; |
|
2280 |
int preLen = negativePrefix.length(); |
|
2281 |
if ((preLen > 0) && result.startsWith(negativePrefix)) { |
|
2282 |
isNegative = true; |
|
2283 |
result = result.substring(preLen); |
|
2284 |
} |
|
2285 |
int sufLen = negativeSuffix.length(); |
|
2286 |
if ((sufLen > 0) && result.endsWith(negativeSuffix)) { |
|
2287 |
isNegative = true; |
|
2288 |
result = result.substring(result.length() - sufLen, |
|
2289 |
result.length()); |
|
2290 |
} |
|
2291 |
if (result.equals(nanString)) |
|
2292 |
result = "NaN"; |
|
2293 |
if (result.equals(infinityString)) |
|
2294 |
result = "Infinity"; |
|
2295 |
if (isNegative) |
|
2296 |
result = "-" + result; |
|
2297 |
||
2298 |
// Translate non-ASCII digits |
|
2299 |
Matcher m = NON_ASCII_DIGIT.matcher(result); |
|
2300 |
if (m.find()) { |
|
2301 |
StringBuilder inASCII = new StringBuilder(); |
|
2302 |
for (int i=0; i<result.length(); i++) { |
|
2303 |
char nextChar = result.charAt(i); |
|
2304 |
if (Character.isDigit(nextChar)) { |
|
2305 |
int d = Character.digit(nextChar, 10); |
|
2306 |
if (d != -1) |
|
2307 |
inASCII.append(d); |
|
2308 |
else |
|
2309 |
inASCII.append(nextChar); |
|
2310 |
} else { |
|
2311 |
inASCII.append(nextChar); |
|
2312 |
} |
|
2313 |
} |
|
2314 |
result = inASCII.toString(); |
|
2315 |
} |
|
2316 |
||
2317 |
return result; |
|
2318 |
} |
|
2319 |
||
2320 |
/** |
|
2321 |
* Returns true if the next token in this scanner's input can be |
|
2322 |
* interpreted as a float value using the {@link #nextFloat} |
|
2323 |
* method. The scanner does not advance past any input. |
|
2324 |
* |
|
2325 |
* @return true if and only if this scanner's next token is a valid |
|
2326 |
* float value |
|
2327 |
* @throws IllegalStateException if this scanner is closed |
|
2328 |
*/ |
|
2329 |
public boolean hasNextFloat() { |
|
2330 |
setRadix(10); |
|
2331 |
boolean result = hasNext(floatPattern()); |
|
2332 |
if (result) { // Cache it |
|
2333 |
try { |
|
2334 |
String s = processFloatToken(hasNextResult); |
|
2335 |
typeCache = Float.valueOf(Float.parseFloat(s)); |
|
2336 |
} catch (NumberFormatException nfe) { |
|
2337 |
result = false; |
|
2338 |
} |
|
2339 |
} |
|
2340 |
return result; |
|
2341 |
} |
|
2342 |
||
2343 |
/** |
|
2344 |
* Scans the next token of the input as a <tt>float</tt>. |
|
2345 |
* This method will throw <code>InputMismatchException</code> |
|
2346 |
* if the next token cannot be translated into a valid float value as |
|
2347 |
* described below. If the translation is successful, the scanner advances |
|
2348 |
* past the input that matched. |
|
2349 |
* |
|
2350 |
* <p> If the next token matches the <a |
|
2351 |
* href="#Float-regex"><i>Float</i></a> regular expression defined above |
|
2352 |
* then the token is converted into a <tt>float</tt> value as if by |
|
2353 |
* removing all locale specific prefixes, group separators, and locale |
|
2354 |
* specific suffixes, then mapping non-ASCII digits into ASCII |
|
2355 |
* digits via {@link Character#digit Character.digit}, prepending a |
|
2356 |
* negative sign (-) if the locale specific negative prefixes and suffixes |
|
2357 |
* were present, and passing the resulting string to |
|
2358 |
* {@link Float#parseFloat Float.parseFloat}. If the token matches |
|
2359 |
* the localized NaN or infinity strings, then either "Nan" or "Infinity" |
|
2360 |
* is passed to {@link Float#parseFloat(String) Float.parseFloat} as |
|
2361 |
* appropriate. |
|
2362 |
* |
|
2363 |
* @return the <tt>float</tt> scanned from the input |
|
2364 |
* @throws InputMismatchException |
|
2365 |
* if the next token does not match the <i>Float</i> |
|
2366 |
* regular expression, or is out of range |
|
2367 |
* @throws NoSuchElementException if input is exhausted |
|
2368 |
* @throws IllegalStateException if this scanner is closed |
|
2369 |
*/ |
|
2370 |
public float nextFloat() { |
|
2371 |
// Check cached result |
|
2372 |
if ((typeCache != null) && (typeCache instanceof Float)) { |
|
2373 |
float val = ((Float)typeCache).floatValue(); |
|
2374 |
useTypeCache(); |
|
2375 |
return val; |
|
2376 |
} |
|
2377 |
setRadix(10); |
|
2378 |
clearCaches(); |
|
2379 |
try { |
|
2380 |
return Float.parseFloat(processFloatToken(next(floatPattern()))); |
|
2381 |
} catch (NumberFormatException nfe) { |
|
2382 |
position = matcher.start(); // don't skip bad token |
|
2383 |
throw new InputMismatchException(nfe.getMessage()); |
|
2384 |
} |
|
2385 |
} |
|
2386 |
||
2387 |
/** |
|
2388 |
* Returns true if the next token in this scanner's input can be |
|
2389 |
* interpreted as a double value using the {@link #nextDouble} |
|
2390 |
* method. The scanner does not advance past any input. |
|
2391 |
* |
|
2392 |
* @return true if and only if this scanner's next token is a valid |
|
2393 |
* double value |
|
2394 |
* @throws IllegalStateException if this scanner is closed |
|
2395 |
*/ |
|
2396 |
public boolean hasNextDouble() { |
|
2397 |
setRadix(10); |
|
2398 |
boolean result = hasNext(floatPattern()); |
|
2399 |
if (result) { // Cache it |
|
2400 |
try { |
|
2401 |
String s = processFloatToken(hasNextResult); |
|
2402 |
typeCache = Double.valueOf(Double.parseDouble(s)); |
|
2403 |
} catch (NumberFormatException nfe) { |
|
2404 |
result = false; |
|
2405 |
} |
|
2406 |
} |
|
2407 |
return result; |
|
2408 |
} |
|
2409 |
||
2410 |
/** |
|
2411 |
* Scans the next token of the input as a <tt>double</tt>. |
|
2412 |
* This method will throw <code>InputMismatchException</code> |
|
2413 |
* if the next token cannot be translated into a valid double value. |
|
2414 |
* If the translation is successful, the scanner advances past the input |
|
2415 |
* that matched. |
|
2416 |
* |
|
2417 |
* <p> If the next token matches the <a |
|
2418 |
* href="#Float-regex"><i>Float</i></a> regular expression defined above |
|
2419 |
* then the token is converted into a <tt>double</tt> value as if by |
|
2420 |
* removing all locale specific prefixes, group separators, and locale |
|
2421 |
* specific suffixes, then mapping non-ASCII digits into ASCII |
|
2422 |
* digits via {@link Character#digit Character.digit}, prepending a |
|
2423 |
* negative sign (-) if the locale specific negative prefixes and suffixes |
|
2424 |
* were present, and passing the resulting string to |
|
2425 |
* {@link Double#parseDouble Double.parseDouble}. If the token matches |
|
2426 |
* the localized NaN or infinity strings, then either "Nan" or "Infinity" |
|
2427 |
* is passed to {@link Double#parseDouble(String) Double.parseDouble} as |
|
2428 |
* appropriate. |
|
2429 |
* |
|
2430 |
* @return the <tt>double</tt> scanned from the input |
|
2431 |
* @throws InputMismatchException |
|
2432 |
* if the next token does not match the <i>Float</i> |
|
2433 |
* regular expression, or is out of range |
|
2434 |
* @throws NoSuchElementException if the input is exhausted |
|
2435 |
* @throws IllegalStateException if this scanner is closed |
|
2436 |
*/ |
|
2437 |
public double nextDouble() { |
|
2438 |
// Check cached result |
|
2439 |
if ((typeCache != null) && (typeCache instanceof Double)) { |
|
2440 |
double val = ((Double)typeCache).doubleValue(); |
|
2441 |
useTypeCache(); |
|
2442 |
return val; |
|
2443 |
} |
|
2444 |
setRadix(10); |
|
2445 |
clearCaches(); |
|
2446 |
// Search for next float |
|
2447 |
try { |
|
2448 |
return Double.parseDouble(processFloatToken(next(floatPattern()))); |
|
2449 |
} catch (NumberFormatException nfe) { |
|
2450 |
position = matcher.start(); // don't skip bad token |
|
2451 |
throw new InputMismatchException(nfe.getMessage()); |
|
2452 |
} |
|
2453 |
} |
|
2454 |
||
2455 |
// Convenience methods for scanning multi precision numbers |
|
2456 |
||
2457 |
/** |
|
2458 |
* Returns true if the next token in this scanner's input can be |
|
2459 |
* interpreted as a <code>BigInteger</code> in the default radix using the |
|
2460 |
* {@link #nextBigInteger} method. The scanner does not advance past any |
|
2461 |
* input. |
|
2462 |
* |
|
2463 |
* @return true if and only if this scanner's next token is a valid |
|
2464 |
* <code>BigInteger</code> |
|
2465 |
* @throws IllegalStateException if this scanner is closed |
|
2466 |
*/ |
|
2467 |
public boolean hasNextBigInteger() { |
|
2468 |
return hasNextBigInteger(defaultRadix); |
|
2469 |
} |
|
2470 |
||
2471 |
/** |
|
2472 |
* Returns true if the next token in this scanner's input can be |
|
2473 |
* interpreted as a <code>BigInteger</code> in the specified radix using |
|
2474 |
* the {@link #nextBigInteger} method. The scanner does not advance past |
|
2475 |
* any input. |
|
2476 |
* |
|
2477 |
* @param radix the radix used to interpret the token as an integer |
|
2478 |
* @return true if and only if this scanner's next token is a valid |
|
2479 |
* <code>BigInteger</code> |
|
2480 |
* @throws IllegalStateException if this scanner is closed |
|
2481 |
*/ |
|
2482 |
public boolean hasNextBigInteger(int radix) { |
|
2483 |
setRadix(radix); |
|
2484 |
boolean result = hasNext(integerPattern()); |
|
2485 |
if (result) { // Cache it |
|
2486 |
try { |
|
2487 |
String s = (matcher.group(SIMPLE_GROUP_INDEX) == null) ? |
|
2488 |
processIntegerToken(hasNextResult) : |
|
2489 |
hasNextResult; |
|
2490 |
typeCache = new BigInteger(s, radix); |
|
2491 |
} catch (NumberFormatException nfe) { |
|
2492 |
result = false; |
|
2493 |
} |
|
2494 |
} |
|
2495 |
return result; |
|
2496 |
} |
|
2497 |
||
2498 |
/** |
|
2499 |
* Scans the next token of the input as a {@link java.math.BigInteger |
|
2500 |
* BigInteger}. |
|
2501 |
* |
|
2502 |
* <p> An invocation of this method of the form |
|
2503 |
* <tt>nextBigInteger()</tt> behaves in exactly the same way as the |
|
2504 |
* invocation <tt>nextBigInteger(radix)</tt>, where <code>radix</code> |
|
2505 |
* is the default radix of this scanner. |
|
2506 |
* |
|
2507 |
* @return the <tt>BigInteger</tt> scanned from the input |
|
2508 |
* @throws InputMismatchException |
|
2509 |
* if the next token does not match the <i>Integer</i> |
|
2510 |
* regular expression, or is out of range |
|
2511 |
* @throws NoSuchElementException if the input is exhausted |
|
2512 |
* @throws IllegalStateException if this scanner is closed |
|
2513 |
*/ |
|
2514 |
public BigInteger nextBigInteger() { |
|
2515 |
return nextBigInteger(defaultRadix); |
|
2516 |
} |
|
2517 |
||
2518 |
/** |
|
2519 |
* Scans the next token of the input as a {@link java.math.BigInteger |
|
2520 |
* BigInteger}. |
|
2521 |
* |
|
2522 |
* <p> If the next token matches the <a |
|
2523 |
* href="#Integer-regex"><i>Integer</i></a> regular expression defined |
|
2524 |
* above then the token is converted into a <tt>BigInteger</tt> value as if |
|
2525 |
* by removing all group separators, mapping non-ASCII digits into ASCII |
|
2526 |
* digits via the {@link Character#digit Character.digit}, and passing the |
|
2527 |
* resulting string to the {@link |
|
2528 |
* java.math.BigInteger#BigInteger(java.lang.String) |
|
2529 |
* BigInteger(String, int)} constructor with the specified radix. |
|
2530 |
* |
|
2531 |
* @param radix the radix used to interpret the token |
|
2532 |
* @return the <tt>BigInteger</tt> scanned from the input |
|
2533 |
* @throws InputMismatchException |
|
2534 |
* if the next token does not match the <i>Integer</i> |
|
2535 |
* regular expression, or is out of range |
|
2536 |
* @throws NoSuchElementException if the input is exhausted |
|
2537 |
* @throws IllegalStateException if this scanner is closed |
|
2538 |
*/ |
|
2539 |
public BigInteger nextBigInteger(int radix) { |
|
2540 |
// Check cached result |
|
2541 |
if ((typeCache != null) && (typeCache instanceof BigInteger) |
|
2542 |
&& this.radix == radix) { |
|
2543 |
BigInteger val = (BigInteger)typeCache; |
|
2544 |
useTypeCache(); |
|
2545 |
return val; |
|
2546 |
} |
|
2547 |
setRadix(radix); |
|
2548 |
clearCaches(); |
|
2549 |
// Search for next int |
|
2550 |
try { |
|
2551 |
String s = next(integerPattern()); |
|
2552 |
if (matcher.group(SIMPLE_GROUP_INDEX) == null) |
|
2553 |
s = processIntegerToken(s); |
|
2554 |
return new BigInteger(s, radix); |
|
2555 |
} catch (NumberFormatException nfe) { |
|
2556 |
position = matcher.start(); // don't skip bad token |
|
2557 |
throw new InputMismatchException(nfe.getMessage()); |
|
2558 |
} |
|
2559 |
} |
|
2560 |
||
2561 |
/** |
|
2562 |
* Returns true if the next token in this scanner's input can be |
|
2563 |
* interpreted as a <code>BigDecimal</code> using the |
|
2564 |
* {@link #nextBigDecimal} method. The scanner does not advance past any |
|
2565 |
* input. |
|
2566 |
* |
|
2567 |
* @return true if and only if this scanner's next token is a valid |
|
2568 |
* <code>BigDecimal</code> |
|
2569 |
* @throws IllegalStateException if this scanner is closed |
|
2570 |
*/ |
|
2571 |
public boolean hasNextBigDecimal() { |
|
2572 |
setRadix(10); |
|
2573 |
boolean result = hasNext(decimalPattern()); |
|
2574 |
if (result) { // Cache it |
|
2575 |
try { |
|
2576 |
String s = processFloatToken(hasNextResult); |
|
2577 |
typeCache = new BigDecimal(s); |
|
2578 |
} catch (NumberFormatException nfe) { |
|
2579 |
result = false; |
|
2580 |
} |
|
2581 |
} |
|
2582 |
return result; |
|
2583 |
} |
|
2584 |
||
2585 |
/** |
|
2586 |
* Scans the next token of the input as a {@link java.math.BigDecimal |
|
2587 |
* BigDecimal}. |
|
2588 |
* |
|
2589 |
* <p> If the next token matches the <a |
|
2590 |
* href="#Decimal-regex"><i>Decimal</i></a> regular expression defined |
|
2591 |
* above then the token is converted into a <tt>BigDecimal</tt> value as if |
|
2592 |
* by removing all group separators, mapping non-ASCII digits into ASCII |
|
2593 |
* digits via the {@link Character#digit Character.digit}, and passing the |
|
2594 |
* resulting string to the {@link |
|
2595 |
* java.math.BigDecimal#BigDecimal(java.lang.String) BigDecimal(String)} |
|
2596 |
* constructor. |
|
2597 |
* |
|
2598 |
* @return the <tt>BigDecimal</tt> scanned from the input |
|
2599 |
* @throws InputMismatchException |
|
2600 |
* if the next token does not match the <i>Decimal</i> |
|
2601 |
* regular expression, or is out of range |
|
2602 |
* @throws NoSuchElementException if the input is exhausted |
|
2603 |
* @throws IllegalStateException if this scanner is closed |
|
2604 |
*/ |
|
2605 |
public BigDecimal nextBigDecimal() { |
|
2606 |
// Check cached result |
|
2607 |
if ((typeCache != null) && (typeCache instanceof BigDecimal)) { |
|
2608 |
BigDecimal val = (BigDecimal)typeCache; |
|
2609 |
useTypeCache(); |
|
2610 |
return val; |
|
2611 |
} |
|
2612 |
setRadix(10); |
|
2613 |
clearCaches(); |
|
2614 |
// Search for next float |
|
2615 |
try { |
|
2616 |
String s = processFloatToken(next(decimalPattern())); |
|
2617 |
return new BigDecimal(s); |
|
2618 |
} catch (NumberFormatException nfe) { |
|
2619 |
position = matcher.start(); // don't skip bad token |
|
2620 |
throw new InputMismatchException(nfe.getMessage()); |
|
2621 |
} |
|
2622 |
} |
|
2623 |
||
2624 |
/** |
|
2625 |
* Resets this scanner. |
|
2626 |
* |
|
2627 |
* <p> Resetting a scanner discards all of its explicit state |
|
2628 |
* information which may have been changed by invocations of {@link |
|
2629 |
* #useDelimiter}, {@link #useLocale}, or {@link #useRadix}. |
|
2630 |
* |
|
2631 |
* <p> An invocation of this method of the form |
|
2632 |
* <tt>scanner.reset()</tt> behaves in exactly the same way as the |
|
2633 |
* invocation |
|
2634 |
* |
|
2635 |
* <blockquote><pre> |
|
2636 |
* scanner.useDelimiter("\\p{javaWhitespace}+") |
|
2637 |
* .useLocale(Locale.getDefault()) |
|
2638 |
* .useRadix(10); |
|
2639 |
* </pre></blockquote> |
|
2640 |
* |
|
2641 |
* @return this scanner |
|
2642 |
* |
|
2643 |
* @since 1.6 |
|
2644 |
*/ |
|
2645 |
public Scanner reset() { |
|
2646 |
delimPattern = WHITESPACE_PATTERN; |
|
2647 |
useLocale(Locale.getDefault()); |
|
2648 |
useRadix(10); |
|
2649 |
clearCaches(); |
|
2650 |
return this; |
|
2651 |
} |
|
2652 |
} |