In this Java File IO tutorial, you will understand how the Scanner class works with various examples which you can use for your daily Java coding.

 

* How does a Scanner work?

Basically, a Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace (blanks, tabs, and line terminators). The parsed tokens can be converted into primitive types and Strings using various next methods. Here’s the simplest example of using a Scanner to read an integer number from the user:

Scanner scanner = new Scanner(System.in);
int number = scanner.nextInt();
Let’s understand how to create an instance of a Scanner and its primary methods.

 

* How to construct a Scanner?

We can create an instance of the Scanner class to parse a byte input stream, a character input stream or a String, using one of the following constructors (to name a few):

  • Scanner(File source): constructs a Scanner to scan the specified file using the system’s default charset.
  • Scanner(File source, String charsetName): constructs a Scanner to scan the specified file using the specified character set.
  • Scanner(InputStream source): constructs a Scanner from a byte input stream using the system’s default charset.
  • Scanner(InputStream source, String charsetName): constructs a Scanner from a byte input stream using the specified charset.
  • Scanner(Readable source): constructs a Scanner from a character stream.
  • Scanner(String source): constructs a Scanner from a String.
Note that these constructors throw FileNotFoundException if the specified file does not exist, or IllegalArgumentException if the specified charset is not found.

 

* Scanner’s Primary Methods:

The Scanner class provides various methods for reading tokens from an input source. We can also use different delimiter and locale. Here are its methods (to name a few):



The hasNext() method returns true if the scanner has another token in its input.

The hasNextXXX() method returns true if the next token can be converted to the specified type, e.g. the hasNextInt()method returns true if the next token can be converted to an integer number. Here are such methods (to name a few):

  • hasNextBoolean()
  • hasNextByte()
  • hasNextDouble()
  • hasNextFloat()
These methods throw IllegalStateException if the scanner is closed.

The next()method returns the next token as a String.

The nextXXX()method return the next token as a value of the specified type. Here to name a few:

  • boolean nextBoolean()
  • byte nextByte()
  • double nextDouble()
  • float nextFloat()
These methods throw InputMismatchException if the next token cannot be converted to the specified type; throw NoSuchElementException if the input is exhausted; and throw IllegalStateException if the scanner is closed.

The useDelimiter(String pattern)method specifies a delimiter different than the default whitespace. It’s also possible to use a regular expression as a delimiter for more advanced parsing.

The useLocale(Locale) method specifies a locale which is different than the system’s default locale.

The skip(String pattern) method skips an input that matches the pattern. This can be useful in as we don’t want to parse a certain input.

 

* Closing the Scanner:

We should close the Scanner after use by invoking its close()method. Since the Scanner class implements the AutoCloseable interface, we can use it with the try-with-resources structure to let the compiler adds the code to close it implicitly.

Next, we show you various examples using the Scanner class.

 

1. Using Scanner to Read User’s Input

A common use of Scanner is reading input from the user in command-line environment, as its nextXXX() methods are more convenient than the Console’s  readLine() method which returns only String. Here’s the example:

Scanner scanner = new Scanner(System.in);

System.out.print("What's your name? ");
String name = scanner.next();

System.out.print("How old are you? ");
int age = scanner.nextInt();

System.out.print("What is value of PI? ");
float pi = scanner.nextFloat();


System.out.println("Your name is: " + name);
System.out.println("Your age is: " + age);
System.out.println("Your PI is: " + pi);

scanner.close();
Here, we use the Scanner class to read a String, an integer number and a float number.

 

2. Using Scanner to Read Numbers from File

The following code parses all numbers from a text file and then sums them up:

Scanner scanner = new Scanner(new File("numbers.txt"));

int sum = 0;

while (scanner.hasNextInt()) {
	sum += scanner.nextInt();
}

scanner.close();

System.out.println("Sum = " + sum);
Run this code with a file having the following content:

84 90 89 78 54 45 90 2007 443 404 500 1394
And it will print the sum:

Sum = 5278
 

3. Using Scanner to Read a Text File line by line

The following code uses the nextLine() method to read a text file line by line, and add all lines to a list of Strings:

Scanner scanner = new Scanner(new File("tasks.txt"));

List<String> listLines = new ArrayList<>();

while (scanner.hasNext()) {
	String line = scanner.nextLine();
	listLines.add(line);
}

System.out.println(listLines);
scanner.close();
 

4. Using Different Delimiter for Scanner

The following code uses the delimiter comma (,) to parse a CSV file:

Scanner scanner = new Scanner(new File("books.csv"));
scanner.useDelimiter(",");

while (scanner.hasNext()) {
	String title = scanner.next();
	title = title.trim();	// trim the line terminator character
	String author = scanner.next();
	float price = scanner.nextFloat();

	System.out.format("Title: %s; Author: %s; Price: %.2f%n",
						title, author, price);
}

scanner.close();
Given the following CSV file:

Head First Java,Kathy Sierra,23.99,
Effective Java,Joshua Bloch,27.88,
Code Complete,Steve McConnell,38.42,
It produces the following output:

Title: Head First Java; Author: Kathy Sierra; Price: 23.99
Title: Effective Java; Author: Joshua Bloch; Price: 27.88
Title: Code Complete; Author: Steve McConnell; Price: 38.42
 

5. Using Regular Expressions for Scanner

In the following code, we use regular expressions to find only Strings containing the world ‘Java’:

Scanner scanner = new Scanner(new File("books.txt"));
scanner.useDelimiter("[\r\n]");

String pattern = ".*Java.*";

while (scanner.hasNext()) {
	if (scanner.hasNext(pattern)) {
		String javaBook = scanner.next(pattern);
		System.out.println(javaBook);
	} else {
		scanner.next();
	}
}

scanner.close();
Here, we use a regular expression for the delimiter: [\r\n] meaning that the delimiter is new line character (either \r or \n); and the regular expression .*Java.* is to check if the input contains the word ‘Java’.

Given the following text file:

Thinking in Java
The Passionate Programmer
Head First Java
Effective Java
Code Complete 
Core Java Programming
The above code gives the following output:

Thinking in Java
Head First Java
Effective Java
Core Java Programming
 

6. Skipping a certain input for Scanner

The following code uses the skip() method with a regular expression to skip the first word in a String and parses the rest normally:

Scanner scanner = new Scanner("Java is Write Once Run Any Where");
scanner.skip("\\w+");

while (scanner.hasNext()) {
	System.out.println(scanner.next());
}
 

7. Using Different Locale for Scanner

The following code uses a Scanner with French locale to parse numbers from a text file:

Scanner scanner = new Scanner(new File("FrenchNumbers.txt"));
scanner.useLocale(Locale.FRENCH);

while (scanner.hasNextDouble()) {
	double number = scanner.nextDouble();
	System.out.println(number);
}

scanner.close();
Given the following text file (in French locale):

123,5	
456,89	
200,99	
318,12
It gives the following output (in US locale):

123.5
456.89
200.99
318.12
 

API References:

 

Related Tutorials:

 

Other Java File IO Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.



Add comment

   


Comments 

#1Hend Alshehhi2021-03-01 03:01
I want to know how to qr scan
Quote