How do I fix an InputMismatchException error that comes from scanner incorrectly reading a file?

后端 未结 1 1210
無奈伤痛
無奈伤痛 2021-01-22 04:35

I am trying to simply read the first thing in a file and set a variable to hold that value. The first line of the file is 10 (see below) and I am using .nextI

相关标签:
1条回答
  • 2021-01-22 05:33

    It's because you're passing in a string (that contains the filename) to Scanner which it interprets literally. So if fileName = "test.txt", all your scanner contains is "test.txt" (and not the contents of the file). So when you do scanner.nextInt(), it throws an exception as there is no next ints to be found (you'd only be able to scanner.next() to get the fileName back). However, what you want to do is pass in a file handler (using File) into Scanner, which'll then read the contents of the file into the stream which you can then manipulate like you're trying to.

    What you want to do is:

    try {
        File file = new File(fileName);
    }
    catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    Scanner inStream = new Scanner(file);
    

    This'll read in the file contents into the Scanner allowing you do do what you're expecting. (Note: File comes from java.io.File)

    0 讨论(0)
提交回复
热议问题