The scanner is simply not useful in this case. Under the hood, it does all kinds of parsing, validation, caching, and much more. If your case simply "iterates over all lines of the file", use something based on a simple BufferedReader.
In your specific case, I recommend using Files.lines.
Example:
long count = Files.lines(Paths.get("testfile.txt")) .filter(s -> s.contains("particularString")) .count(); System.out.println(count);
(Note that this particular case of streaming api probably does not cover what you are actually trying to achieve - unfortunately your question does not indicate what the result of this method should be.)
On my system, I get about 15% of the Scanner runtime with Files.lines () or a buffered reader.
source share