-
Notifications
You must be signed in to change notification settings - Fork 668
/
Scanner.java
3232 lines (2967 loc) · 124 KB
/
Scanner.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.util;
import java.io.*;
import java.math.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
import java.nio.file.Path;
import java.nio.file.Files;
import java.text.*;
import java.text.spi.NumberFormatProvider;
import java.util.function.Consumer;
import java.util.regex.*;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import sun.util.locale.provider.LocaleProviderAdapter;
import sun.util.locale.provider.ResourceBundleBasedAdapter;
/**
* A simple text scanner which can parse primitive types and strings using
* regular expressions.
*
* <p>A {@code Scanner} breaks its input into tokens using a
* delimiter pattern, which by default matches whitespace. The resulting
* tokens may then be converted into values of different types using the
* various {@code next} methods.
*
* <p>For example, this code allows a user to read a number from
* {@code System.in}:
* <blockquote><pre>{@code
* Scanner sc = new Scanner(System.in);
* int i = sc.nextInt();
* }</pre></blockquote>
*
* <p>As another example, this code allows {@code long} types to be
* assigned from entries in a file {@code myNumbers}:
* <blockquote><pre>{@code
* Scanner sc = new Scanner(new File("myNumbers"));
* while (sc.hasNextLong()) {
* long aLong = sc.nextLong();
* }
* }</pre></blockquote>
*
* <p>The scanner can also use delimiters other than whitespace. This
* example reads several items in from a string:
* <blockquote><pre>{@code
* String input = "1 fish 2 fish red fish blue fish";
* Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
* System.out.println(s.nextInt());
* System.out.println(s.nextInt());
* System.out.println(s.next());
* System.out.println(s.next());
* s.close();
* }</pre></blockquote>
* <p>
* prints the following output:
* <blockquote><pre>{@code
* 1
* 2
* red
* blue
* }</pre></blockquote>
*
* <p>The same output can be generated with this code, which uses a regular
* expression to parse all four tokens at once:
* <blockquote><pre>{@code
* String input = "1 fish 2 fish red fish blue fish";
* Scanner s = new Scanner(input);
* s.findInLine("(\\d+) fish (\\d+) fish (\\w+) fish (\\w+)");
* MatchResult result = s.match();
* for (int i=1; i<=result.groupCount(); i++)
* System.out.println(result.group(i));
* s.close();
* }</pre></blockquote>
*
* <p>The <a id="default-delimiter">default whitespace delimiter</a> used
* by a scanner is as recognized by {@link Character#isWhitespace(char)
* Character.isWhitespace()}. The {@link #reset reset()}
* method will reset the value of the scanner's delimiter to the default
* whitespace delimiter regardless of whether it was previously changed.
*
* <p>A scanning operation may block waiting for input.
*
* <p>The {@link #next} and {@link #hasNext} methods and their
* companion methods (such as {@link #nextInt} and
* {@link #hasNextInt}) first skip any input that matches the delimiter
* pattern, and then attempt to return the next token. Both {@code hasNext()}
* and {@code next()} methods may block waiting for further input. Whether a
* {@code hasNext()} method blocks has no connection to whether or not its
* associated {@code next()} method will block. The {@link #tokens} method
* may also block waiting for input.
*
* <p>The {@link #findInLine findInLine()},
* {@link #findWithinHorizon findWithinHorizon()},
* {@link #skip skip()}, and {@link #findAll findAll()}
* methods operate independently of the delimiter pattern. These methods will
* attempt to match the specified pattern with no regard to delimiters in the
* input and thus can be used in special circumstances where delimiters are
* not relevant. These methods may block waiting for more input.
*
* <p>When a scanner throws an {@link InputMismatchException}, the scanner
* will not pass the token that caused the exception, so that it may be
* retrieved or skipped via some other method.
*
* <p>Depending upon the type of delimiting pattern, empty tokens may be
* returned. For example, the pattern {@code "\\s+"} will return no empty
* tokens since it matches multiple instances of the delimiter. The delimiting
* pattern {@code "\\s"} could return empty tokens since it only passes one
* space at a time.
*
* <p> A scanner can read text from any object which implements the {@link
* java.lang.Readable} interface. If an invocation of the underlying
* readable's {@link java.lang.Readable#read read()} method throws an {@link
* java.io.IOException} then the scanner assumes that the end of the input
* has been reached. The most recent {@code IOException} thrown by the
* underlying readable can be retrieved via the {@link #ioException} method.
*
* <p>When a {@code Scanner} is closed, it will close its input source
* if the source implements the {@link java.io.Closeable} interface.
*
* <p>A {@code Scanner} is not safe for multithreaded use without
* external synchronization.
*
* <p>Unless otherwise mentioned, passing a {@code null} parameter into
* any method of a {@code Scanner} will cause a
* {@code NullPointerException} to be thrown.
*
* <p>A scanner will default to interpreting numbers as decimal unless a
* different radix has been set by using the {@link #useRadix} method. The
* {@link #reset} method will reset the value of the scanner's radix to
* {@code 10} regardless of whether it was previously changed.
*
* <h3> <a id="localized-numbers">Localized numbers</a> </h3>
*
* <p> An instance of this class is capable of scanning numbers in the standard
* formats as well as in the formats of the scanner's locale. A scanner's
* <a id="initial-locale">initial locale </a>is the value returned by the {@link
* java.util.Locale#getDefault(Locale.Category)
* Locale.getDefault(Locale.Category.FORMAT)} method; it may be changed via the {@link
* #useLocale useLocale()} method. The {@link #reset} method will reset the value of the
* scanner's locale to the initial locale regardless of whether it was
* previously changed.
*
* <p>The localized formats are defined in terms of the following parameters,
* which for a particular locale are taken from that locale's {@link
* java.text.DecimalFormat DecimalFormat} object, {@code df}, and its and
* {@link java.text.DecimalFormatSymbols DecimalFormatSymbols} object,
* {@code dfs}.
*
* <blockquote><dl>
* <dt><i>LocalGroupSeparator </i>
* <dd>The character used to separate thousands groups,
* <i>i.e.,</i> {@code dfs.}{@link
* java.text.DecimalFormatSymbols#getGroupingSeparator
* getGroupingSeparator()}
* <dt><i>LocalDecimalSeparator </i>
* <dd>The character used for the decimal point,
* <i>i.e.,</i> {@code dfs.}{@link
* java.text.DecimalFormatSymbols#getDecimalSeparator
* getDecimalSeparator()}
* <dt><i>LocalPositivePrefix </i>
* <dd>The string that appears before a positive number (may
* be empty), <i>i.e.,</i> {@code df.}{@link
* java.text.DecimalFormat#getPositivePrefix
* getPositivePrefix()}
* <dt><i>LocalPositiveSuffix </i>
* <dd>The string that appears after a positive number (may be
* empty), <i>i.e.,</i> {@code df.}{@link
* java.text.DecimalFormat#getPositiveSuffix
* getPositiveSuffix()}
* <dt><i>LocalNegativePrefix </i>
* <dd>The string that appears before a negative number (may
* be empty), <i>i.e.,</i> {@code df.}{@link
* java.text.DecimalFormat#getNegativePrefix
* getNegativePrefix()}
* <dt><i>LocalNegativeSuffix </i>
* <dd>The string that appears after a negative number (may be
* empty), <i>i.e.,</i> {@code df.}{@link
* java.text.DecimalFormat#getNegativeSuffix
* getNegativeSuffix()}
* <dt><i>LocalNaN </i>
* <dd>The string that represents not-a-number for
* floating-point values,
* <i>i.e.,</i> {@code dfs.}{@link
* java.text.DecimalFormatSymbols#getNaN
* getNaN()}
* <dt><i>LocalInfinity </i>
* <dd>The string that represents infinity for floating-point
* values, <i>i.e.,</i> {@code dfs.}{@link
* java.text.DecimalFormatSymbols#getInfinity
* getInfinity()}
* </dl></blockquote>
*
* <h4> <a id="number-syntax">Number syntax</a> </h4>
*
* <p> The strings that can be parsed as numbers by an instance of this class
* are specified in terms of the following regular-expression grammar, where
* Rmax is the highest digit in the radix being used (for example, Rmax is 9 in base 10).
*
* <dl>
* <dt><i>NonAsciiDigit</i>:
* <dd>A non-ASCII character c for which
* {@link java.lang.Character#isDigit Character.isDigit}{@code (c)}
* returns true
*
* <dt><i>Non0Digit</i>:
* <dd>{@code [1-}<i>Rmax</i>{@code ] | }<i>NonASCIIDigit</i>
*
* <dt><i>Digit</i>:
* <dd>{@code [0-}<i>Rmax</i>{@code ] | }<i>NonASCIIDigit</i>
*
* <dt><i>GroupedNumeral</i>:
* <dd><code>( </code><i>Non0Digit</i>
* <i>Digit</i>{@code ?
* }<i>Digit</i>{@code ?}
* <dd> <code>( </code><i>LocalGroupSeparator</i>
* <i>Digit</i>
* <i>Digit</i>
* <i>Digit</i>{@code )+ )}
*
* <dt><i>Numeral</i>:
* <dd>{@code ( ( }<i>Digit</i>{@code + )
* | }<i>GroupedNumeral</i>{@code )}
*
* <dt><a id="Integer-regex"><i>Integer</i>:</a>
* <dd>{@code ( [-+]? ( }<i>Numeral</i>{@code
* ) )}
* <dd>{@code | }<i>LocalPositivePrefix</i> <i>Numeral</i>
* <i>LocalPositiveSuffix</i>
* <dd>{@code | }<i>LocalNegativePrefix</i> <i>Numeral</i>
* <i>LocalNegativeSuffix</i>
*
* <dt><i>DecimalNumeral</i>:
* <dd><i>Numeral</i>
* <dd>{@code | }<i>Numeral</i>
* <i>LocalDecimalSeparator</i>
* <i>Digit</i>{@code *}
* <dd>{@code | }<i>LocalDecimalSeparator</i>
* <i>Digit</i>{@code +}
*
* <dt><i>Exponent</i>:
* <dd>{@code ( [eE] [+-]? }<i>Digit</i>{@code + )}
*
* <dt><a id="Decimal-regex"><i>Decimal</i>:</a>
* <dd>{@code ( [-+]? }<i>DecimalNumeral</i>
* <i>Exponent</i>{@code ? )}
* <dd>{@code | }<i>LocalPositivePrefix</i>
* <i>DecimalNumeral</i>
* <i>LocalPositiveSuffix</i>
* <i>Exponent</i>{@code ?}
* <dd>{@code | }<i>LocalNegativePrefix</i>
* <i>DecimalNumeral</i>
* <i>LocalNegativeSuffix</i>
* <i>Exponent</i>{@code ?}
*
* <dt><i>HexFloat</i>:
* <dd>{@code [-+]? 0[xX][0-9a-fA-F]*\.[0-9a-fA-F]+
* ([pP][-+]?[0-9]+)?}
*
* <dt><i>NonNumber</i>:
* <dd>{@code NaN
* | }<i>LocalNan</i>{@code
* | Infinity
* | }<i>LocalInfinity</i>
*
* <dt><i>SignedNonNumber</i>:
* <dd>{@code ( [-+]? }<i>NonNumber</i>{@code )}
* <dd>{@code | }<i>LocalPositivePrefix</i>
* <i>NonNumber</i>
* <i>LocalPositiveSuffix</i>
* <dd>{@code | }<i>LocalNegativePrefix</i>
* <i>NonNumber</i>
* <i>LocalNegativeSuffix</i>
*
* <dt><a id="Float-regex"><i>Float</i></a>:
* <dd><i>Decimal</i>
* {@code | }<i>HexFloat</i>
* {@code | }<i>SignedNonNumber</i>
*
* </dl>
* <p>Whitespace is not significant in the above regular expressions.
*
* @since 1.5
*/
// 扫描器,允许从指定的输入源读取数据
public final class Scanner implements Iterator<String>, Closeable {
/** Internal buffer used to hold input */
private CharBuffer buf;
/** Size of internal character buffer */
private static final int BUFFER_SIZE = 1024;
/** The index into the buffer currently held by the Scanner */
private int position;
/** Internal matcher used for finding delimiters */
private Matcher matcher;
/** Pattern used to delimit tokens */
private Pattern delimPattern;
/** Pattern found in last hasNext operation */
private Pattern hasNextPattern;
/** Position after last hasNext operation */
private int hasNextPosition;
/** Result after last hasNext operation */
private String hasNextResult;
/** The input source */
private Readable source;
/** Boolean is true if source is done */
private boolean sourceClosed = false;
/** Boolean indicating more input is required */
private boolean needInput = false;
/** Boolean indicating if a delim has been skipped this operation */
private boolean skipped = false;
/** A store of a position that the scanner may fall back to */
private int savedScannerPosition = -1;
/** A cache of the last primitive type scanned */
private Object typeCache = null;
/** Boolean indicating if a match result is available */
private boolean matchValid = false;
/** Boolean indicating if this scanner has been closed */
private boolean closed = false;
/** The current radix used by this scanner */
private int radix = 10;
/** The default radix for this scanner */
private int defaultRadix = 10;
/** The locale used by this scanner */
private Locale locale = null;
/** A cache of the last few recently used Patterns */
private PatternLRUCache patternCache = new PatternLRUCache(7);
/** A holder of the last IOException encountered */
private IOException lastException;
/**
* Number of times this scanner's state has been modified.
* Generally incremented on most public APIs and checked within spliterator implementations.
*/
int modCount;
/** A pattern for java whitespace */
private static Pattern WHITESPACE_PATTERN = Pattern.compile("\\p{javaWhitespace}+"); // Character.isWhitespace()
/** A pattern for any token */
private static Pattern FIND_ANY_PATTERN = Pattern.compile("(?s).*");
/** A pattern for non-ASCII digits */
private static Pattern NON_ASCII_DIGIT = Pattern.compile("[\\p{javaDigit}&&[^0-9]]");
// Fields and methods to support scanning primitive types
/**
* Locale dependent values used to scan numbers
*/
private String groupSeparator = "\\,";
private String decimalSeparator = "\\.";
private String nanString = "NaN";
private String infinityString = "Infinity";
private String positivePrefix = "";
private String negativePrefix = "\\-";
private String positiveSuffix = "";
private String negativeSuffix = "";
/**
* Fields and an accessor method to match booleans
*/
private static volatile Pattern boolPattern;
private static final String BOOLEAN_PATTERN = "true|false";
private static Pattern boolPattern() {
Pattern bp = boolPattern;
if(bp == null) {
boolPattern = bp = Pattern.compile(BOOLEAN_PATTERN, Pattern.CASE_INSENSITIVE);
}
return bp;
}
/**
* Fields and methods to match bytes, shorts, ints, and longs
*/
private Pattern integerPattern;
private String digits = "0123456789abcdefghijklmnopqrstuvwxyz";
private String non0Digit = "[\\p{javaDigit}&&[^0]]";
private int SIMPLE_GROUP_INDEX = 5;
private String buildIntegerPatternString() {
String radixDigits = digits.substring(0, radix);
// \\p{javaDigit} is not guaranteed to be appropriate
// here but what can we do? The final authority will be
// whatever parse method is invoked, so ultimately the
// Scanner will do the right thing
String digit = "((?i)[" + radixDigits + "]|\\p{javaDigit})";
String groupedNumeral = "(" + non0Digit + digit + "?" + digit + "?(" + groupSeparator + digit + digit + digit + ")+)";
// digit++ is the possessive form which is necessary for reducing
// backtracking that would otherwise cause unacceptable performance
String numeral = "(("+ digit+"++)|"+groupedNumeral+")";
String javaStyleInteger = "([-+]?(" + numeral + "))";
String negativeInteger = negativePrefix + numeral + negativeSuffix;
String positiveInteger = positivePrefix + numeral + positiveSuffix;
return "(" + javaStyleInteger + ")|(" + positiveInteger + ")|(" + negativeInteger + ")";
}
private Pattern integerPattern() {
if (integerPattern == null) {
integerPattern = patternCache.forName(buildIntegerPatternString());
}
return integerPattern;
}
/**
* Fields and an accessor method to match line separators
*/
private static volatile Pattern separatorPattern;
private static volatile Pattern linePattern;
private static final String LINE_SEPARATOR_PATTERN = "\r\n|[\n\r\u2028\u2029\u0085]";
private static final String LINE_PATTERN = ".*(" + LINE_SEPARATOR_PATTERN + ")|.+$";
private static Pattern separatorPattern() {
Pattern sp = separatorPattern;
if(sp == null) {
separatorPattern = sp = Pattern.compile(LINE_SEPARATOR_PATTERN);
}
return sp;
}
private static Pattern linePattern() {
Pattern lp = linePattern;
if(lp == null) {
linePattern = lp = Pattern.compile(LINE_PATTERN);
}
return lp;
}
/**
* Fields and methods to match floats and doubles
*/
private Pattern floatPattern;
private Pattern decimalPattern;
private void buildFloatAndDecimalPattern() {
// \\p{javaDigit} may not be perfect, see above
String digit = "([0-9]|(\\p{javaDigit}))";
String exponent = "([eE][+-]?" + digit + "+)?";
String groupedNumeral = "(" + non0Digit + digit + "?" + digit + "?(" + groupSeparator + digit + digit + digit + ")+)";
// Once again digit++ is used for performance, as above
String numeral = "((" + digit + "++)|" + groupedNumeral + ")";
String decimalNumeral = "(" + numeral + "|" + numeral + decimalSeparator + digit + "*+|" + decimalSeparator + digit + "++)";
String nonNumber = "(NaN|" + nanString + "|Infinity|" + infinityString + ")";
String positiveFloat = "(" + positivePrefix + decimalNumeral + positiveSuffix + exponent + ")";
String negativeFloat = "(" + negativePrefix + decimalNumeral + negativeSuffix + exponent + ")";
String decimal = "(([-+]?" + decimalNumeral + exponent + ")|" + positiveFloat + "|" + negativeFloat + ")";
String hexFloat = "[-+]?0[xX][0-9a-fA-F]*\\.[0-9a-fA-F]+([pP][-+]?[0-9]+)?";
String positiveNonNumber = "(" + positivePrefix + nonNumber + positiveSuffix + ")";
String negativeNonNumber = "(" + negativePrefix + nonNumber + negativeSuffix + ")";
String signedNonNumber = "(([-+]?" + nonNumber + ")|" + positiveNonNumber + "|" + negativeNonNumber + ")";
floatPattern = Pattern.compile(decimal + "|" + hexFloat + "|" + signedNonNumber);
decimalPattern = Pattern.compile(decimal);
}
private Pattern floatPattern() {
if(floatPattern == null) {
buildFloatAndDecimalPattern();
}
return floatPattern;
}
private Pattern decimalPattern() {
if(decimalPattern == null) {
buildFloatAndDecimalPattern();
}
return decimalPattern;
}
/*▼ 构造器 ████████████████████████████████████████████████████████████████████████████████┓ */
/*
* 扫描器的输入源是多样化的,包括:InputStream、File、Path、ReadableByteChannel、String、Readable。
* 解码字节流时可以指定预设的字符编码,也可以使用JVM默认的字符编码。
*/
/**
* Constructs a new {@code Scanner} that produces values scanned
* from the specified input stream. Bytes from the stream are converted
* into characters using the underlying platform's
* {@linkplain java.nio.charset.Charset#defaultCharset() default charset}.
*
* @param source An input stream to be scanned
*/
public Scanner(InputStream source) {
this(new InputStreamReader(source), WHITESPACE_PATTERN);
}
/**
* Constructs a new {@code Scanner} that produces values scanned
* from the specified input stream. Bytes from the stream are converted
* into characters using the specified charset.
*
* @param source An input stream to be scanned
* @param charsetName The encoding type used to convert bytes from the
* stream into characters to be scanned
*
* @throws IllegalArgumentException if the specified character set
* does not exist
*/
public Scanner(InputStream source, String charsetName) {
this(source, toCharset(charsetName));
}
/**
* Constructs a new {@code Scanner} that produces values scanned
* from the specified input stream. Bytes from the stream are converted
* into characters using the specified charset.
*
* @param source an input stream to be scanned
* @param charset the charset used to convert bytes from the file
* into characters to be scanned
*
* @since 10
*/
public Scanner(InputStream source, Charset charset) {
this(makeReadable(Objects.requireNonNull(source, "source"), charset), WHITESPACE_PATTERN);
}
/**
* Constructs a new {@code Scanner} that produces values scanned
* from the specified file. Bytes from the file are converted into
* characters using the underlying platform's
* {@linkplain java.nio.charset.Charset#defaultCharset() default charset}.
*
* @param source A file to be scanned
*
* @throws FileNotFoundException if source is not found
*/
public Scanner(File source) throws FileNotFoundException {
this(new FileInputStream(source).getChannel());
}
/**
* Constructs a new {@code Scanner} that produces values scanned
* from the specified file. Bytes from the file are converted into
* characters using the specified charset.
*
* @param source A file to be scanned
* @param charsetName The encoding type used to convert bytes from the file
* into characters to be scanned
*
* @throws FileNotFoundException if source is not found
* @throws IllegalArgumentException if the specified encoding is
* not found
*/
public Scanner(File source, String charsetName) throws FileNotFoundException {
this(Objects.requireNonNull(source), toDecoder(charsetName));
}
/**
* Constructs a new {@code Scanner} that produces values scanned
* from the specified file. Bytes from the file are converted into
* characters using the specified charset.
*
* @param source A file to be scanned
* @param charset The charset used to convert bytes from the file
* into characters to be scanned
*
* @throws IOException if an I/O error occurs opening the source
* @since 10
*/
public Scanner(File source, Charset charset) throws IOException {
this(Objects.requireNonNull(source), charset.newDecoder());
}
/**
* Constructs a new {@code Scanner} that produces values scanned
* from the specified file. Bytes from the file are converted into
* characters using the underlying platform's
* {@linkplain java.nio.charset.Charset#defaultCharset() default charset}.
*
* @param source the path to the file to be scanned
*
* @throws IOException if an I/O error occurs opening source
* @since 1.7
*/
public Scanner(Path source) throws IOException {
this(Files.newInputStream(source));
}
/**
* Constructs a new {@code Scanner} that produces values scanned
* from the specified file. Bytes from the file are converted into
* characters using the specified charset.
*
* @param source the path to the file to be scanned
* @param charsetName The encoding type used to convert bytes from the file
* into characters to be scanned
*
* @throws IOException if an I/O error occurs opening source
* @throws IllegalArgumentException if the specified encoding is not found
* @since 1.7
*/
public Scanner(Path source, String charsetName) throws IOException {
this(Objects.requireNonNull(source), toCharset(charsetName));
}
/**
* Constructs a new {@code Scanner} that produces values scanned
* from the specified file. Bytes from the file are converted into
* characters using the specified charset.
*
* @param source the path to the file to be scanned
* @param charset the charset used to convert bytes from the file
* into characters to be scanned
*
* @throws IOException if an I/O error occurs opening the source
* @since 10
*/
public Scanner(Path source, Charset charset) throws IOException {
this(makeReadable(source, charset));
}
/**
* Constructs a new {@code Scanner} that produces values scanned
* from the specified channel. Bytes from the source are converted into
* characters using the underlying platform's
* {@linkplain java.nio.charset.Charset#defaultCharset() default charset}.
*
* @param source A channel to scan
*/
public Scanner(ReadableByteChannel source) {
this(makeReadable(Objects.requireNonNull(source, "source")), WHITESPACE_PATTERN);
}
/**
* Constructs a new {@code Scanner} that produces values scanned
* from the specified channel. Bytes from the source are converted into
* characters using the specified charset.
*
* @param source A channel to scan
* @param charsetName The encoding type used to convert bytes from the
* channel into characters to be scanned
*
* @throws IllegalArgumentException if the specified character set
* does not exist
*/
public Scanner(ReadableByteChannel source, String charsetName) {
this(makeReadable(Objects.requireNonNull(source, "source"), toDecoder(charsetName)), WHITESPACE_PATTERN);
}
/**
* Constructs a new {@code Scanner} that produces values scanned
* from the specified channel. Bytes from the source are converted into
* characters using the specified charset.
*
* @param source a channel to scan
* @param charset the encoding type used to convert bytes from the
* channel into characters to be scanned
*
* @since 10
*/
public Scanner(ReadableByteChannel source, Charset charset) {
this(makeReadable(Objects.requireNonNull(source, "source"), charset), WHITESPACE_PATTERN);
}
/**
* Constructs a new {@code Scanner} that produces values scanned
* from the specified string.
*
* @param source A string to scan
*/
public Scanner(String source) {
this(new StringReader(source), WHITESPACE_PATTERN);
}
/**
* Constructs a new {@code Scanner} that produces values scanned
* from the specified source.
*
* @param source A character source implementing the {@link Readable} interface
*/
public Scanner(Readable source) {
this(Objects.requireNonNull(source, "source"), WHITESPACE_PATTERN);
}
/**
* Constructs a {@code Scanner} that returns values scanned
* from the specified source delimited by the specified pattern.
*
* @param source A character source implementing the Readable interface
* @param pattern A delimiting pattern
*/
private Scanner(Readable source, Pattern pattern) {
assert source != null : "source should not be null";
assert pattern != null : "pattern should not be null";
this.source = source;
delimPattern = pattern;
buf = CharBuffer.allocate(BUFFER_SIZE);
buf.limit(0);
matcher = delimPattern.matcher(buf);
matcher.useTransparentBounds(true); // 使用透明边界
matcher.useAnchoringBounds(false); // 不使用锚点边界
useLocale(Locale.getDefault(Locale.Category.FORMAT));
}
private Scanner(File source, CharsetDecoder dec) throws FileNotFoundException {
this(makeReadable(new FileInputStream(source).getChannel(), dec));
}
/*▲ 构造器 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ hasNext ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Returns true if the next token in this scanner's input can be
* interpreted as a boolean value using a case insensitive pattern
* created from the string "true|false". The scanner does not
* advance past the input that matched.
*
* @return true if and only if this scanner's next token is a valid
* boolean value
*
* @throws IllegalStateException if this scanner is closed
*/
// 判断下一个元素是否为boolean值
public boolean hasNextBoolean() {
return hasNext(boolPattern());
}
/**
* Returns true if the next token in this scanner's input can be
* interpreted as a byte value in the default radix using the
* {@link #nextByte} method. The scanner does not advance past any input.
*
* @return true if and only if this scanner's next token is a valid
* byte value
*
* @throws IllegalStateException if this scanner is closed
*/
// 判断下一个元素是否为byte值(10进制)
public boolean hasNextByte() {
return hasNextByte(defaultRadix);
}
/**
* Returns true if the next token in this scanner's input can be
* interpreted as a short value in the default radix using the
* {@link #nextShort} method. The scanner does not advance past any input.
*
* @return true if and only if this scanner's next token is a valid
* short value in the default radix
*
* @throws IllegalStateException if this scanner is closed
*/
// 判断下一个元素是否为short值(10进制)
public boolean hasNextShort() {
return hasNextShort(defaultRadix);
}
/**
* Returns true if the next token in this scanner's input can be
* interpreted as an int value in the default radix using the
* {@link #nextInt} method. The scanner does not advance past any input.
*
* @return true if and only if this scanner's next token is a valid
* int value
*
* @throws IllegalStateException if this scanner is closed
*/
// 判断下一个元素是否为int值(10进制)
public boolean hasNextInt() {
return hasNextInt(defaultRadix);
}
/**
* Returns true if the next token in this scanner's input can be
* interpreted as a long value in the default radix using the
* {@link #nextLong} method. The scanner does not advance past any input.
*
* @return true if and only if this scanner's next token is a valid
* long value
*
* @throws IllegalStateException if this scanner is closed
*/
// 判断下一个元素是否为long值(10进制)
public boolean hasNextLong() {
return hasNextLong(defaultRadix);
}
/**
* Returns true if the next token in this scanner's input can be
* interpreted as a float value using the {@link #nextFloat}
* method. The scanner does not advance past any input.
*
* @return true if and only if this scanner's next token is a valid
* float value
*
* @throws IllegalStateException if this scanner is closed
*/
// 判断下一个元素是否为float值
public boolean hasNextFloat() {
setRadix(10);
boolean result = hasNext(floatPattern());
if(result) { // Cache it
try {
String s = processFloatToken(hasNextResult);
typeCache = Float.valueOf(Float.parseFloat(s));
} catch(NumberFormatException nfe) {
result = false;
}
}
return result;
}
/**
* Returns true if the next token in this scanner's input can be
* interpreted as a double value using the {@link #nextDouble}
* method. The scanner does not advance past any input.
*
* @return true if and only if this scanner's next token is a valid
* double value
*
* @throws IllegalStateException if this scanner is closed
*/
// 判断下一个元素是否为double值
public boolean hasNextDouble() {
setRadix(10);
boolean result = hasNext(floatPattern());
if(result) { // Cache it
try {
String s = processFloatToken(hasNextResult);
typeCache = Double.valueOf(Double.parseDouble(s));
} catch(NumberFormatException nfe) {
result = false;
}
}
return result;
}
/**
* Returns true if the next token in this scanner's input can be
* interpreted as a {@code BigInteger} in the default radix using the
* {@link #nextBigInteger} method. The scanner does not advance past any
* input.
*
* @return true if and only if this scanner's next token is a valid
* {@code BigInteger}
*
* @throws IllegalStateException if this scanner is closed
*/
// 判断下一个元素是否为BigInteger值(10进制)
public boolean hasNextBigInteger() {
return hasNextBigInteger(defaultRadix);
}
/**
* Returns true if the next token in this scanner's input can be
* interpreted as a {@code BigDecimal} using the
* {@link #nextBigDecimal} method. The scanner does not advance past any
* input.
*
* @return true if and only if this scanner's next token is a valid
* {@code BigDecimal}
*
* @throws IllegalStateException if this scanner is closed
*/
// 判断下一个元素是否为BigDecimal值
public boolean hasNextBigDecimal() {
setRadix(10);
boolean result = hasNext(decimalPattern());
if(result) { // Cache it
try {
String s = processFloatToken(hasNextResult);
typeCache = new BigDecimal(s);
} catch(NumberFormatException nfe) {
result = false;
}
}
return result;
}
/**
* Returns true if the next token in this scanner's input can be
* interpreted as a byte value in the specified radix using the
* {@link #nextByte} method. The scanner does not advance past any input.
*
* <p>If the radix is less than {@link Character#MIN_RADIX Character.MIN_RADIX}
* or greater than {@link Character#MAX_RADIX Character.MAX_RADIX}, then an
* {@code IllegalArgumentException} is thrown.
*
* @param radix the radix used to interpret the token as a byte value
*
* @return true if and only if this scanner's next token is a valid
* byte value
*
* @throws IllegalStateException if this scanner is closed
* @throws IllegalArgumentException if the radix is out of range
*/
// 判断下一个元素是否为byte值,进制由参数radix指定
public boolean hasNextByte(int radix) {
setRadix(radix);
boolean result = hasNext(integerPattern());
if(result) { // Cache it
try {
String s = (matcher.group(SIMPLE_GROUP_INDEX) == null) ? processIntegerToken(hasNextResult) : hasNextResult;
typeCache = Byte.parseByte(s, radix);
} catch(NumberFormatException nfe) {
result = false;
}
}
return result;
}
/**
* Returns true if the next token in this scanner's input can be
* interpreted as a short value in the specified radix using the
* {@link #nextShort} method. The scanner does not advance past any input.
*
* <p>If the radix is less than {@link Character#MIN_RADIX Character.MIN_RADIX}
* or greater than {@link Character#MAX_RADIX Character.MAX_RADIX}, then an
* {@code IllegalArgumentException} is thrown.
*
* @param radix the radix used to interpret the token as a short value
*
* @return true if and only if this scanner's next token is a valid
* short value in the specified radix
*
* @throws IllegalStateException if this scanner is closed
* @throws IllegalArgumentException if the radix is out of range
*/
// 判断下一个元素是否为short值,进制由参数radix指定
public boolean hasNextShort(int radix) {
setRadix(radix);
boolean result = hasNext(integerPattern());
if(result) { // Cache it
try {
String s = (matcher.group(SIMPLE_GROUP_INDEX) == null) ? processIntegerToken(hasNextResult) : hasNextResult;
typeCache = Short.parseShort(s, radix);
} catch(NumberFormatException nfe) {
result = false;
}
}
return result;
}
/**
* Returns true if the next token in this scanner's input can be
* interpreted as an int value in the specified radix using the
* {@link #nextInt} method. The scanner does not advance past any input.
*
* <p>If the radix is less than {@link Character#MIN_RADIX Character.MIN_RADIX}
* or greater than {@link Character#MAX_RADIX Character.MAX_RADIX}, then an
* {@code IllegalArgumentException} is thrown.
*
* @param radix the radix used to interpret the token as an int value
*
* @return true if and only if this scanner's next token is a valid
* int value
*
* @throws IllegalStateException if this scanner is closed
* @throws IllegalArgumentException if the radix is out of range
*/