×

Java Programs

Java Practice

Java program to read content from file using BufferedReader

This program will read and print the content of the file using BufferedReader class. There is a file in same directory where program is saved, file name is "file2.txt". This program will read and print the content of this file using BufferReader class.

BufferReader takes the FileReader type argument and FileReader class defines that file. So we have to create mainly three object:

  • A File object to define the filename.
  • A FileReader object to define the File using File Object.
  • A BufferedReader objcet with respect of FileReader object.

BufferedReader.readLine() - This method is used to read a line from the file.

BufferedReader.close() - To close the file.

Program will read content from the file line by line until null is not found.

Read Content from file using BufferedReader in Java

// Java program to read content from file 
// using BufferedReader

import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;

public class ExBufferedReader {
  public static void main(String args[]) {
    final String fileName = "file2.txt";

    try {
      File objFile = new File(fileName);
      if (objFile.exists() == false) {
        System.out.println("File does not exist!!!");
        System.exit(0);
      }

      //reading content from file
      String text;
      int val;

      FileReader objFR = new FileReader(objFile.getAbsoluteFile());
      BufferedReader objBR = new BufferedReader(objFR);
      //read text from file
      System.out.println("Content of the file is: ");
      while ((text = objBR.readLine()) != null) {
        System.out.println(text);
      }

      objBR.close();
    } catch (Exception Ex) {
      System.out.println("Exception : " + Ex.toString());
    }
  }
}

Output

    
Content of the file is: 
Computer is an Electronic Device.

Java File Handling Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.