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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
package com.wilddiary.fileio; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class FileIOExample { public static void main(String[] args) throws FileNotFoundException { try(Scanner scanner = new Scanner(new File("/Users/XYZ/filename.txt"))) { String content = scanner.useDelimiter("\\Z").next(); System.out.println(content); } } } |