I'd like to read data from a txt
file, but I get InputMismatchException
when I call nextDouble()
method. Even though I am using the useLocale
method, but it doesn't work.
The txt file first line is: 1;forname;1.9
public class SimpleFileReader {
public static void main(String[] args){
readFromFile();
}
public static void readFromFile(){
try {
int x = 0;
File file = new File("read.txt");
Scanner sc = new Scanner(file).useDelimiter(";|\\n");
sc.useLocale(Locale.FRENCH);
while (sc.hasNext()){
System.out.println(sc.nextInt()+" "+sc.next()+" "+sc.nextDouble());
x++;
}
System.out.println("lines: "+x);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Blame the French locale: it uses comma as a decimal separator, so
1.9
fails to parse.Replacing
1.9
with1,9
fixes the problem (demo 1). If you would like to parse1.9
, useLocale.US
instead ofLocale.FRENCH
(demo 2).A second problem in your code is the use of
\\n
as the separator. You should use a single backslash, otherwise words that containn
would break your parsing logic.