• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
  • Skip to footer
  • Core Java
  • Design Patterns
  • JSP
  • Servlets
  • Building Tools
  • jQuery
  • Spring
  • Hibernate
  • Mongo DB
  • More
    • HTML
    • SCJP
    • AJAX
    • UML
    • Struts
    • J2EE
    • Testing
    • Angular JS

J2EE Reference

  • Home
  • About Us
    • Java Learning Centers
  • Contact Us

Scanner

July 20, 2012 By j2eereference Leave a Comment

Scanner class in Java

Scanner class is added in J2SE5 .This is used to read formatted input and convert into binary form.

Why scanner ?

We know that it is possible to read formatted input from file or console. But it requires lot of programing effort. Scanner simplifies this.

Scanner constructors

Scanner can be  created for different input source like String,InputStream or any object that implements Readable or ReadableByteChannel.

1
2
FileReader fr= new FileReader("sample.txt");
Scanner scanner=new Scanner(fr);

This works because FileReader implements Readable interface.

1
Scanner scanner=new Scanner(System.in);

This works because System.in an object of InputStream.

Scanner can read String also as below

1
2
String str="This is from j2eereference.com";
Scanner scanner= new Scanner(str);

Scanner provide two types of methods to read input . hasNextX and nextX , where X is the type of the data., like HasNextInt,hasNextDouble. next method will throw NoSuchElementException if next method cannot find the type of data it is looking for.

Now lets see some example code to read different types of inputs.

Reading String using scanner :

1
2
3
4
5
6
7
8
9
10
11
12
import java.util.Scanner;
 
public class ScannerDemo {
public static void main(String[] args) {
 
String str = "This is from j2eereference.com";
Scanner scanner = new Scanner(str);
while (scanner.hasNext()) {
System.out.println("Item :" + scanner.next());
}
}
}

output

Item :This
Item :is
Item :from
Item :j2eereference.com

Reading int values using Scanner

1
2
3
4
5
6
7
8
9
10
11
12
13
import java.util.Scanner;
 
public class ScannerDemo {
public static void main(String[] args) {
int item;
String str = "10 20 30 40";
Scanner scanner = new Scanner(str);
while (scanner.hasNextInt()) {
item=scanner.nextInt();
System.out.println("Item :" +item);
}
}
}

Output

Item :10
Item :20
Item :30
Item :40

Reading data  from file using Scanner

Here in this example we will create a file called sample.txt and write different types of data into it. In this scenario we will have to check the type of the data while reading.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
 
public class ScannerDemo {
public static void main(String[] args) throws IOException {
FileWriter fout = new FileWriter("sample.txt");
fout.write("j2eereference.com true 10.5");
fout.close();
FileInputStream fin = new FileInputStream("sample.txt");
Scanner scanner = new Scanner(fin);
while (scanner.hasNext()) {
if (scanner.hasNextBoolean())
System.out.println("Boolean : " + scanner.nextBoolean());
if (scanner.hasNextDouble())
System.out.println("Double : " + scanner.nextDouble());
if (scanner.hasNext())
System.out.println("String : " + scanner.next());
}
fin.close();
}
}

Output

String : j2eereference.com
Boolean : true
Double : 10.5

Setting Delimiter:

We can define where the token starts and ends with the following method

Scanner useDelimiter(String pattern);

Scanner useDelimiter(Pattern pattern); // Here pattern is the regular expression that specify the delimiter set

Now lets see an example using delimiter

1
2
3
4
5
6
7
8
9
10
11
12
13
import java.util.Scanner;
 
public class ScannerDemo {
public static void main(String[] args) {
 
String str = "10#20#30#40";
Scanner scanner = new Scanner(str);
scanner.useDelimiter("#");
while (scanner.hasNextInt()) {
System.out.println("Item :" + scanner.nextInt());
}
}
}

Output

Item :10
Item :20
Item :30
Item :40

Related Posts

  • Busy Spinning in mutithreading
  • Implementing queue in java
  • TreeSet vs ConcurrentSkipListSet
  • How to create immutable class?
  • Implementing Stack in java
  • What is ReentrantLock?
  • What is Semaphore in java
  • Why AtomicInteger class
  • What is CyclicBarrier?
  • CountDownLatch in java

Filed Under: Core Java

Reader Interactions

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

FOLLOW US ONLINE

  • View J2eereference-166104970118637’s profile on Facebook
  • View j2eereference’s profile on Twitter
  • View j2eereference’s profile on LinkedIn

Subscribe by email

Recent posts

  • What is parallel Stream
  • reduce method of the Stream class
  • Difference between the findFirst() and findAny() method
  • intern() method of String class
  • SOLID – Five principles of object-oriented software design
  • Java Coding Best Practices
  • How to use lambda expression effectively
  • Enhanced pseudo-Random Number Generators in java17
  • How to use Foreign-Memory Access API
  • Pattern Matching for instanceof
  • Text Blocks – Feature added in Java17
  • Record – The new feature added in java 17
  • What is Sealed Class
  • Features added in Java 17
  • Java Buzzwords

Footer

Core Java
Design Patterns
JSP
Servlets
HTML
Building Tools
AJAX
SCJP
jQuery
Testing
Spring
UML
Struts
Java Centers
Java Training
Home
About Us
Contact Us
Copyright © j2eereference.com. All right reserved.