Java Basics

Java Scanner example

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

The Scanner 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 various useDelimiter methods. Finally, the Scanner class contains the reset method that restores the scanner’s delimiter value to whitespace.

 

Scanner constructors

The Java Scanner 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, the Scanner class provides the next and hasNext 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 a Scanner 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:

This
is
an
input
file
that
contains
multiple
lines
to
be
read
by
a
Java
Scanner.

This
is
a
sample
string
that
is
about
to
be
scanned!

Scanner and different types

A Scanner in Java can be used in order to read different type of values. For example, if an input file contains integer numbers, the Scanner provides the hasNextInt and nextInt methods that check and read an integer number from the input file respectively. The Scanner 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 the Scanner, it is strongly recommended that you close the Scanner using the close method. Once an instance of the Scanner 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 that Scanners 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.

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

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

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button