Java Program to Read the Content of a File Line by Line

To understand this example, you should have the knowledge of the following Java programming topics:


Example 1: Java Program to Read File Using BufferedInputStream

Output

First Line
Second Line
Third Line
Fourth Line
Fifth Line

In the above example, we have used the BufferedInputStream Class to read each line from the file named input.txt.

Note: In order to run this file, you should have a file named input.txt in your current working directory.


Example 2: Java Program to Read File Using BufferedReader

Output

Data in the file: 
First Line
Second Line
Third Line
Fourth Line
Fifth Line

In the above example, we have used the BufferedReader Class to read the file named input.txt.


Example 3: Java Program to Read File Using Scanner

Output

Reading File Using Scanner:
First Line
Second Line
Third Line
Fourth Line
Fifth Line

In the above example, we have created an object of File class named file. We then created a Scanner object associated with the file.

Here, we have used the scanner methods

  • hasNextLine() - returns true if there is next line in the file
  • nextLine() - returns the entire line from the file

To learn more on scanner, visit Java Scanner.