Read file using BufferedReader class - Java

Q. Write a program to read the file using BufferedReader class.

Answer:

BufferedReader class uses two methods for reading the file. One is readLine() method and another is read() method.

In this example of BufferedReader class, we are using both methods to read the file. The name of the text file is "test.txt".

BufferedReaderDemo.java

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

class BufferedReaderDemo
{
     public static void main(String[] args)
     {
          BufferedReader br1 = null;
          BufferedReader br2 = null;
          try
          {
               br1 = new BufferedReader (new FileReader("test.txt"));
               System.out.println("Using readLine () method");
               String content = br1.readLine();
               while (content != null)
               {
                    System.out.println(content);
                    content = br1.readLine();
               }
               br2 = new BufferedReader (new FileReader("test.txt"));
               System.out.println("Using read() method");
               int i = 0;
               char ch;
               while ((i = br2.read()) != -1)
               {
                    ch = (char)i;
                    System.out.print(ch);
               }
          }
          catch (IOException ioe)
          {
               ioe.printStackTrace();
          }
     }
}


Output:

bufferedreader