Java open and read text file

Hi there!! Welcome to flower brackets blog. In this post we are going to learn java open and read text file.

java open text file

In java we have many ways to open and read text file. For that we can use BufferedReader and FileReader class.

Also read – java if else

First let’s see java program reading text file from FileReader using BufferedReader


public class OpenReadFile
   public static void main(String[] args) throws IOException 
      File fl = new File("D:\\JavaProject\\sachin\\demo.txt"); 
      BufferedReader read = new BufferedReader(new FileReader(fl));
      String str;
      while((str = read.readLine()) != null)

In the above java program we have used FileReader and BufferedReader. BufferedReader class has method readLine() which reads text from character-input stream.

It provides buffering of data for quick reading and hence efficient in reading characters and arrays.

Then each line is read using readLine() method and assigned to String variable “str”. Lastly IOException is used to handle specific exceptions.

Using FileReader class


public class OpenReadDemo 
   public static void main(String[] args) throws Exception 
      FileReader file = new FileReader("D:\\JavaProject\\sachin\\demo.txt");
      int a; 
      while((a = != -1)
         System.out.print((char) a);

In the above java program we have used FileReader class. It’s a convenience class for reading character files.

The constructors of this class assume that the default character encoding and the default byte-buffersize are appropriate.

To specify these values yourself, construct an InputStreamReader on a FileInputStream.

FileReader is meant for reading streams of characters. For reading streams of raw bytes, consider using a FileInputStream.

Related Posts