How to read a file line by line

      No Comments on How to read a file line by line




A file can be read line by line using BufferedReader. BufferedReader has a readLine() method which reads a line from a file.
BufferedReader creates a buffering character-input stream that uses a default-sized input buffer.
BufferedReader exists in java.io package.

BufferedReader can be created as following :

BufferedReader can be created by passing Reader object in the constructor of BufferedReader.

File file = new File("abc.txt");
FileReader fileReader = new FileReader(file); 
BufferedReader bfr = new BufferedReader(fileReader);

Signature of readLine() Method:

String java.io.BufferedReader.readLine() throws IOException

How does BufferedReader knows that line has ended ??

BufferedReader considers a line terminated if it encounters any one of the following:
(I.) line feed (‘\n’),
(II.) carriage return (‘\r’),
(III.) carriage return followed immediately by a linefeed.

Demo Examples: Read File Using BufferedReader

package com.masterjavatutorial;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class TestExample {
	
	public static void main(String[] args){
	    
		 File file = new File("/root/Desktop/Blogs_Content/abc.txt");
		 
		 try {
			FileReader fileReader = new FileReader(file); 
			BufferedReader bfr = new BufferedReader(fileReader);
			String str = null;
			while((str = bfr.readLine()) != null){
			   System.out.println(str);
			}
			bfr.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) { 
			e.printStackTrace();
		}
	
	}
	
}

Output of the above program is as below:

This is demo 
program
to read content 
line by line