In this tutorial, we will learn how to read file in Java. 4 easy ways will be used :

1- BufferedReader

Since JDK 1.1

The first easy way to read file is by using the BufferedReader class from the java.io package. Below an example :

Make sure you close the file in the end of the program, otherwise it will be locked and not readable by other process.

2- Scanner

Since JDK 1.5

The second way is to use Scanner from the java.util package. Useful if you want to parse lines and break it into tokens using patterns.

3- Try with resources

Since JDK 1.7

The try with resources statement ensures that each resource is closed at the end of the statement. No need to use finally block to ensure the closing of the resource. You can either use it with BufferedReader or Scanner.

4- Apache commons IO

Since JDK 1.6 For Commons IO 2.4

Since JDK 1.5 For Commons IO 2.2

You can also use the Apache Commons IO library to read file in Java. To do this, add the following dependency to your pom.xml

The Apache Commons IO library offers the FileUtils class to deal with files.  You can either use the method readLines or LineIterator. We will see both.

  • ReadLines

The readLines method returns a list of strings representing each line in the file. The file is always closed at the end. bellow how to use it

  • LineIterator

Iterate over each line of the file. File must be closed in the end of the program.