Java Scanner example
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(Filesource): Constructs a new scanner that produces values scanned from the specified file.Scanner(Stringsource): 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.

Thank you!
We will contact you soon.



