[Solved] java.util.InputMismatchException

Pre-requisite :  Java : Scanner : User input, Parsing and File Reading
Below scanner file reading example throwing “java.util.InputMismatchException” because using scanner.next(regex) but some words in test data  not matching regex “\W” for word as in “Sr. project Lead” in given example.

Test data in file

Saurabh Gupta 36 "Sr project Lead" Noida
Nagar 34 "Project Lead"


package scanner;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ScannerToReadInputFromFile {
	public static void main(String[] args) {
	try {
		// Decalare Scanner and intialize with File input object
		Scanner sc = new Scanner(
		new File("C:\\Users\\Saurabh Gupta\\Desktop\\Data.txt"));
		while (sc.hasNextLine()) {
		} catch (FileNotFoundException ex) {


Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:864)
    at java.util.Scanner.next(Scanner.java:1485)
    at scanner.ScannerToReadInputFromFile.main(ScannerToReadInputFromFile.java:17)

Always handle exception while using regular expressions. In this example pattern is not matching for ‘Sr Project Lead’ because word pattern allow on [A-Za-z0-1] char only.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s