Java Read Text File Line by Line Using BufferedReader / Scanner

In Java Read Text File tutorial, I have explained how to read text file line by line in Java. Below examples are covered in this article.

1). Using BufferedReader & FileReader
2). Using Scanner

1.Using BufferedReader & FileReader classes

BufferedReader provides readLine() method to read file line by line. Below is the to read text file.

package readfile;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class WithBufferReader {

    public void readFile(String path)
    {
        BufferedReader bReader=null;
        try
        {
            FileReader fReader = new FileReader(path);
            String line;

            bReader = new BufferedReader(fReader);

            while((line= bReader.readLine()) != null)
            {
                System.out.println(line);
            }
        }

        catch(FileNotFoundException ex)
        {
            Logger.getLogger(WithBufferReader.class.getName()).log(Level.SEVERE, null, ex);
        }catch (IOException ex) 
        {
            Logger.getLogger(WithBufferReader.class.getName()).log(Level.SEVERE, null, ex);
        }
        finally
        {
            try {
                if(bReader !=null)
                    bReader.close();
            } catch (IOException ex) {
                Logger.getLogger(WithBufferReader.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }
    public static void main(String[] args) {
        // TODO code application logic here

        WithBufferReader readFile = new WithBufferReader();
        readFile.readFile("C:\\textfile.txt");
    }
}

2.Using Scanner class

Using  method nextLine() text file can be read line by line.Normally, Scanner class is used for parsing.

Below is the code to read text file using Scanner.

package readfile;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

public class WithScanner {

  public void readFile(String path)
    {
        try {
            Scanner sc = new Scanner(new File(path));
            while(sc.hasNextLine()) 
            {
               String next = sc.nextLine();
               System.out.println(next);
            }
            sc.close();
        } 
        catch (FileNotFoundException ex) 
        {
            Logger.getLogger(WithScanner.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

     public static void main(String[] args) {

         WithScanner scanner= new WithScanner();

         scanner.readFile("c:\\textfile.txt");

    }
}

References:
1.BufferedReader Doc
2.Scanner Doc