ADVERTISEMENT
ADVERTISEMENT

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 »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.