How to read file line by line in Java
There are following ways to read a file line by line.
- BufferedReader Class
- Scanner class
Using BufferedReader Class
Using the Java BufferedRedaer class is the most common and simple way to read a file line by line in Java. It belongs to java.io package. Java BufferedReader class provides readLine() method to read a file line by line. The signature of the method is:
The method reads a line of text. It returns a string containing the contents of the line. The line must be terminated by any one of a line feed (“n”) or carriage return (“r”).
Example of read a file line by line using BufferedReader class
In the following example, Demo.txt is read by FileReader class. The readLine() method of BufferedReader class reads file line by line, and each line appended to StringBuffer, followed by a linefeed. The content of the StringBuffer are then output to the console.
Output:
Using the Scanner class
Java Scanner class provides more utility methods compare to BufferedReader class. Java Scanner class provides the nextLine() method to facilitates line by line of file’s content. The nextLine() methods returns the same String as readLine() method. The Scanner class can also read a file form InputStream.
Example of read a file line by line using Scanner class
Output: