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
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
)