How to read a file in Java using Scanner

This tutorial shows how to read a file in Java using Scanner class.

The java.util.Scanner can parse text from a variety of input sources like String, File, InputStream, System.in etc. and can break the input into tokens as per the specified delimiter. By default, it uses whitespace as the delimiter.

To read a file in entirety, you can pass file as the input source with the end of file (EOF) character as the delimiter to get the entire file content as one token. Refer the code below.

We are using the feature try-with-resources feature of JDK 7 in the example below. The Scanner object is our resource in this case.  The try-with-resources statement ensures that resource used in the try statement is automatically closed at the end of the statement.

Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource. This saves us from writing the ugly code to release the resource in the finally block making the code cleaner and shorter.

 


 

Leave a Reply

avatar
300
  Subscribe  
Notify of