1+ package com .baeldung .scanner ;
2+
3+ import lombok .extern .log4j .Log4j ;
4+ import org .apache .log4j .LogManager ;
5+ import org .apache .log4j .PropertyConfigurator ;
6+
7+ import java .io .IOException ;
8+ import java .io .InputStream ;
9+ import java .util .Properties ;
10+ import java .util .Scanner ;
11+
12+ @ Log4j
13+ public class HasNextVsHasNextLineDemo {
14+ private static final String LINE = "----------------------------" ;
15+ private static final String END_LINE = "--------OUTPUT--END---------\n " ;
16+
17+
18+ private static final String INPUT = new StringBuilder ()
19+ .append ("magic\t project\n " )
20+ .append (" database: oracle\n " )
21+ .append ("dependencies:\n " )
22+ .append ("spring:foo:bar\n " )
23+ .append ("\n " ).toString ();
24+
25+ private static void hasNextBasic () {
26+ printHeader ("hasNext() Basic" );
27+ Scanner scanner = new Scanner (INPUT );
28+ while (scanner .hasNext ()) {
29+ log .info (scanner .next ());
30+ }
31+ log .info (END_LINE );
32+ scanner .close ();
33+ }
34+
35+ private static void hasNextWithDelimiter () {
36+ printHeader ("hasNext() with delimiter" );
37+ Scanner scanner = new Scanner (INPUT );
38+ while (scanner .hasNext ()) {
39+ String token = scanner .next ();
40+ if ("dependencies:" .equals (token )) {
41+ scanner .useDelimiter (":" );
42+ }
43+ log .info (token );
44+ }
45+ log .info (END_LINE );
46+ scanner .close ();
47+ }
48+
49+ private static void hasNextWithDelimiterFixed () {
50+ printHeader ("hasNext() with delimiter FIX" );
51+ Scanner scanner = new Scanner (INPUT );
52+ while (scanner .hasNext ()) {
53+ String token = scanner .next ();
54+ if ("dependencies:" .equals (token )) {
55+ scanner .useDelimiter (":|\\ s+" );
56+ }
57+ log .info (token );
58+ }
59+ log .info (END_LINE );
60+ scanner .close ();
61+ }
62+
63+ private static void addLineNumber () {
64+ printHeader ("add line number by hasNextLine() " );
65+ Scanner scanner = new Scanner (INPUT );
66+ int i = 0 ;
67+ while (scanner .hasNextLine ()) {
68+ log .info (String .format ("%d|%s" , ++i , scanner .nextLine ()));
69+ }
70+ log .info (END_LINE );
71+ scanner .close ();
72+ }
73+
74+ private static void printHeader (String title ) {
75+ log .info (LINE );
76+ log .info (title );
77+ log .info (LINE );
78+ }
79+
80+ public static void main (String [] args ) throws IOException {
81+ setLogger ();
82+ hasNextBasic ();
83+ hasNextWithDelimiter ();
84+ hasNextWithDelimiterFixed ();
85+ addLineNumber ();
86+ }
87+
88+ //overwrite the logger config
89+ private static void setLogger () throws IOException {
90+ InputStream is = HasNextVsHasNextLineDemo .class .getResourceAsStream ("/scanner/log4j.properties" );
91+ Properties props = new Properties ();
92+ props .load (is );
93+ LogManager .resetConfiguration ();
94+ PropertyConfigurator .configure (props );
95+ }
96+ }
0 commit comments