Java Basics

Java Scanner example

Photo of Sotirios-Efstathios ManeasSotirios-Efstathios ManeasFebruary 14th, 2014Last Updated: February 14th, 2014
0 207 2 minutes read

In this tutorial we will discuss about scanners in Java. AScanner in Java is a simple text scanner which can parse primitive types and strings using regular expressions. AScanner 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.

TheScanner class is defined as final and thus,cannot be extended. As already mentioned, the default delimiter is considered to be the whitespace, but this can change using the varioususeDelimiter methods. Finally, theScanner class contains thereset method that restores the scanner’s delimiter value to whitespace.

 

Scanner constructors

The JavaScanner class contains a number of constructors. In this tutorial we will discuss about two constructors. The first one requires an input file, while the second requires a string. Specifically:

  • Scanner (File source): Constructs a new scanner that produces values scanned from the specified file.
  • Scanner (String source): Constructs a new scanner that produces values scanned from the specified string.

Scanner example

In order to iterate over all matching tokens, theScanner class provides thenext andhasNext methods. In Java, a scanner first skips any input that matches the delimiter pattern and then, attempts to return the next token. Both methods may block waiting for further input.

A sample example that uses aScanner is shown below:

ScannerExample.java:

import java.io.File;import java.io.FileNotFoundException;import java.util.Scanner;public class ScannerExample {public static void readFromFile(String inputFile) throws FileNotFoundException {Scanner scanner = new Scanner(new File(inputFile));while(scanner.hasNext())System.out.println(scanner.next());scanner.close();}public static void readFromString(String inputString) {Scanner scanner = new Scanner(inputString);while(scanner.hasNext())System.out.println(scanner.next());scanner.close();}public static void main(String[] args) throws FileNotFoundException {ScannerExample.readFromFile("inputFile.txt");System.out.println();ScannerExample.readFromString("This is a sample string that is about to be scanned!");}}

A sample execution is shown below:

ThisisaninputfilethatcontainsmultiplelinestobereadbyaJavaScanner.Thisisasamplestringthatisabouttobescanned!

Scanner and different types

AScanner in Java can be used in order to read different type of values. For example, if an input file contains integer numbers, theScanner provides thehasNextInt andnextInt methods that check and read an integer number from the input file respectively. TheScanner class provides methods for all basic types of the Java programming language.

A simple example is shown below:

ScannerSumExample.java:

import java.io.File;import java.io.FileNotFoundException;import java.util.Scanner;public class ScannerSumExample {public static double calculateSum(String inputFile) throws FileNotFoundException {Scanner scanner = new Scanner(new File(inputFile));double sum = 0.0;while (scanner.hasNext()) {if (scanner.hasNextDouble()) {sum += scanner.nextDouble();} else if(scanner.hasNextInt()) {sum += scanner.nextInt();}else {// Ignore the input line.scanner.next();}}scanner.close();return sum;}public static void main(String[] args) throws FileNotFoundException {System.out.println("The total sum equals to: " +ScannerSumExample.calculateSum("numbers.txt"));}}

In this example, as you can observe, we create a sum of those lines that contain either integers or double numbers. The remaining lines that contain strings are ignored.

A simple execution is shown below:

The total sum equals to: 2014.0

Final Comments about Scanners

When you have finished with theScanner, it is strongly recommended that you close theScanner using theclose method. Once an instance of theScanner class is closed, then it can be garbage collected and thus, its memory can be reclaimed and reused.

Furthermore, it is very important to mention thatScanners in Java are not thread-safe and thus, they must be synchronized externally.

Download the Eclipse Project

The Eclipse project of this example:ScannerExample.zip.

 
This was a tutorial about scanners in Java.

Do you want to know how to develop your skillset to become aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to theTerms andPrivacy Policy

Thank you!

We will contact you soon.

Photo of Sotirios-Efstathios ManeasSotirios-Efstathios ManeasFebruary 14th, 2014Last Updated: February 14th, 2014
0 207 2 minutes read
Photo of Sotirios-Efstathios Maneas

Sotirios-Efstathios Maneas

Sotirios-Efstathios (Stathis) Maneas is a PhD student at the Department of Computer Science at the University of Toronto. His main interests include distributed systems, storage systems, file systems, and operating systems.
Subscribe
Notify of
guest
I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.