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
Sailesh
Nagar 34 "Project Lead"
Example
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()) { //System.out.println(sc.next(Pattern.compile("\\w+"))); } } catch (FileNotFoundException ex) { ex.printStackTrace(); } } }Output
Saurabh Gupta 36 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)
Solution
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.