Q:

Java program to read content from file using BufferedReader

belongs to collection: Java File Handling Programs

0

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:

  • File object to define the filename.
  • FileReader object to define the File using File Object.
  • 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.

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java File Handling Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to get file size and file path... >>
<< Java program to write content into file using Buff...