Reading text file in java using scanner

211 views Asked by At

I am a beginner. Reading from text file in Java using a scanner. This code just to read the first 3 tokens isn't working:

try{
Scanner scFile = new Scanner (new File ("readhere.txt")).useDelimiter("#");
String first = scFile.next();
String second = scFile.next();
int third = scFile.nextInt(); // error here. Why cant I store the integer?
}
catch(FileNotFoundException e){
    System.out.println("Error");
}

I am trying to read just the first 3 tokens:

Andrew#Smith#21
John#Morris#55

the problem occurs when reading 21. java.util.InputMismatchException

1

There are 1 answers

1
Reimeus On BEST ANSWER

The scanner is including the carriage return character(s) as part of the next readable token which produces an invalid integer. You could do

Scanner scanner = new Scanner(new File("readhere.txt")).useDelimiter("#|\r\n");