This post will discuss how to read a text file line-by-line in Java.

1. Using BufferedReader class

A simple solution to read a text file line-by-line is using the BufferedReader whose readLine() method can read a line of text. Following is a simple example demonstrating the usage of this method, where each invocation of the readLine() method would read the next line from the file and return it as a string.

Download Code

 
Starting with Java 8, you can use the lines() method that returns a stream of lines of text read from the BufferedReader. This is demonstrated below:

Download Code

2. Using Files class

The Files class consists of several static methods that operate on files. Since JDK 1.8, you can use the static method Files.lines() to get all lines from the file as a Stream. Even though this method returns a Stream, you should not use chaining as we do with other Stream operations. To ensure that the stream is closed promptly after completion of the stream’s operations, you must enclose this method within a try-with-resources statement.

Download Code

 
Alternatively, to get a list of all lines from a file, you can directly use the Files.readAllLines() method. This elegant and concise method is introduced in Java SE 8.

Download Code

3. Using Scanner class

Another option is to use the Scanner class to read each line of the file with the nextLine() method. Following is a simple example demonstrating the usage of this method. Note that the hasNextLine() method returns true only if the scanner has more lines left, and the nextLine() method advances the scanner to the next line and returns the current line.

Download Code

4. Using IOUtils class

If you prefer Apache Commons IO library, you can use the readLines() method from the IOUtils class. It returns the contents of a Reader as a list of strings, one entry per line.

Download Code

That’s all about reading a text file line-by-line in Java.