This post will discuss how to read the contents of a file using Scanner class in Java.

Scanner is a utility class in java.util package which can parse primitive types and strings using regular expressions. It can read text from any object which implements the Readable interface.

 
A plausible way of reading a file in Java is to construct a Scanner that produces values scanned from the specified file. This is demonstrated below:

Download Code

 
We can also construct a Scanner that produces values scanned from the specified file. This is demonstrated below using the try-with-resources block to automatically takes care of scanner.close().

Download Code

That’s all about reading the contents of a file using the Scanner class in Java.

Read More:

Read all text from a file into a String in Java