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.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.
Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
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.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close