So, I just ran into an interesting problem when using the Scanner class to read contents from files. Basically, I'm trying to read several output files generated by a syntax application from a directory to calculate some accuracy metrics.
Basically, my code simply looks at each of the files in the directory and opens them with a scanner to process the contents. For some reason, some of the files (all encoded by UTF-8) were not read by the Scanner. Despite the fact that the files were not empty, scanner.hasNextLine () will return false on the first call (I opened the debugger and noticed this). I initialized the scanner directly with File objects each time (file Objects were successfully created). i.e:
File file = new File(pathName); ... Scanner scanner = new Scanner(file);
I tried a couple of things and eventually managed to fix this problem by initializing the scanner as follows:
Scanner scanner = new Scanner(new FileInputStream(file));
Although Iām happy to have solved the problem, Iām still wondering what could have happened before. Any ideas? Many thanks!
shaunvxc
source share