Different ways of Reading a text file in Java


Reading a text file in Java is a common task for many developers that can be accomplishedusing various classes and methods including the ‘BufferedReader’, ‘Scanner’and ‘FileReader’ classes. In this article, we’ll explore these different ways and provideexamples to help you choose the best approach for your needs. Note that these classesare associated with some exceptions too, therefore, itis necessary to define a catch blockto handle those exceptions

Before moving to the program, create a text file with a suitable name and put some contentinside it. We have created a text file named ‘myTextfile.txt’ in the D drive of local machine.

Using Scanner Class

Scanner is the most used class of ‘java.util’ package that helps to take input from varioussources such as keyboards and files. To read a text file using Scanner, we need to createan instance of File and pass it to the constructor of Scanner as a parameter.

Syntax

Scanner nameOfObject = new Scanner(objectOfFile);

Approach

  • First step is to create an instance of class ‘File’ to store the path of specified file.

  • Now, pass this instance to the constructor of Scanner class.

  • Take a while loop that will check whether the file contains any data or not using the built-in method ‘hasNextLine()’ and then, read the available data using the ‘nextLine()’ method.

Example

The following example illustrates the use of Scanner class to read a text file.

import java.io.*;
import java.util.*;
public class Readtxt1 {
   public static void main(String[] args) {
      try {
         // path of the file
         File flpath = new File("D:/Java Programs/myTextfile.txt");
         Scanner input = new Scanner(flpath);
         while (input.hasNextLine()) { // to check available data
            System.out.println(input.nextLine());
         }
         input.close(); // closing the Scanner
      }
      catch (FileNotFoundException exp) { // to handle exception
         System.out.println("There is error finding file");
      }
   }
}

Output

Welcome to Tutorials Point !!

Using BufferedReader Class

It is mostly used to read characters from input streams like local files and keyboards. To read a text file using BufferedReader, we need to create an instance of class FileReader and pass it to the constructor of BufferedReader as a parameter.

Syntax

BufferedReader nameOfObject = new BufferedReader(objectOfFileReader);

Approach

  • First step is to create an instance of class ‘File’ to store the path of specified file.

  • Now, pass this instance to the constructor of BufferedReader class.

  • Now, declare a String variable to store the information of file with the help of a while loop and the ‘readLine()’ method.

Example

In this example, we will define a static method to perform a multiplication operation. Since it does not accept parameters, we call this method without any argument in the main()method of same class.

import java.io.*;
import java.util.*;
public class Readtxt2 {
   // path of the file
   final static String flpath = "D:/Java Programs/myTextfile.txt";
   public static void main(String[] args) {
      try {
         File filename = new File(flpath);
         BufferedReader bufrd = new BufferedReader( new FileReader(filename));
         String info = null;
         
         // reading the given file
         while( (info = bufrd.readLine()) != null ) {
            System.out.println(info);
         }
      }
      catch (Exception exp) { // to handle exception
         System.out.println("There is error finding file");
      }
   }
}

Output

Welcome to Tutorials Point !!

Using FileReader Class

It uses the default character encoding and byte buffer size for reading information. To read a text file using FileReader, we need to create an instance of class File and pass the file name or path to the constructor FileReader as a parameter.

Syntax

FileReader nameOfObject = new FileReader(objectOfFile);

Approach

  • First step is to create an instance of class ‘File’ to store the path of specified file.

  • Now, pass this instance to the constructor of FileReader class.

  • Now, declare an integer variable to store the information of file with the help of a while loop and the ‘read()’ method.

Example

This example shows the practical implementation of FileReader class to read a text file.

import java.io.*;
import java.util.*;
public class Readtxt3 {
   // path of the file
   final static String flpath = "D:/Java Programs/myTextfile.txt";
   public static void main(String[] args) {
      try {
         File filename = new File(flpath);
         FileReader filerd = new FileReader(filename);
         int info = 0;
         
         // reading the given file
         while( (info = filerd.read()) != -1) {
            System.out.print((char)info); // to convert int to char
         }
      }
      catch (Exception exp) { // to handle exception
         System.out.println("There is error finding file");
      }
   }
}

Output

Welcome to Tutorials Point !!

Conclusion

In this article, we have understood several ways to read a text file in Java. Each method is quite simple and straightforward however, the best approach will depend on the specific needs of your project. We have also seen the practical implementation ofBuffered Reader, Scanner and File Reader classes through example programs.

Updated on: 20-Jul-2023

242 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements