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

import java.io.*;

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)
      {
         System.out.println(str);
      }
      read.close();
   }
}

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

import java.io.FileReader;

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

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