Sotirios-Efstathios Maneas

About Sotirios-Efstathios Maneas

Sotirios-Efstathios (Stathis) Maneas is a postgraduate student at the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. His main interests include distributed systems, web crawling, model checking, operating systems, programming languages and web applications.

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.

Related Whitepaper:

Java Essential Training

Author David Gassner explores Java SE (Standard Edition), the language used to build mobile apps for Android devices, enterprise server applications, and more!

The course demonstrates how to install both Java and the Eclipse IDE and dives into the particulars of programming. The course also explains the fundamentals of Java, from creating simple variables, assigning values, and declaring methods to working with strings, arrays, and subclasses; reading and writing to text files; and implementing object oriented programming concepts. Exercise files are included with the course.

Get it Now!  

Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

15,153 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books