Write a java program to Read content from file using BufferedReader


This program uses a BufferedReader to read the contents of a file and prints them to the console. Here's a breakdown of how it works:

  • The program defines a file_name variable and initializes it to "file.txt".
  • The program creates a File object using the file_name variable. If the file does not exist, the program prints an error message and exits.
  • The program creates a FileReader object using the File object to read the contents of the file.
  • The program creates a BufferedReader object using the FileReader object to buffer the input and make it more efficient.
  • The program uses a while loop to read each line of the file using the readLine() method of the BufferedReader object. The loop continues until there are no more lines to read.
  • For each line, the program prints the line to the console.
  • After reading all the lines, the program closes the BufferedReader.

Note that the program uses try-catch blocks to catch any exceptions that might occur while reading the file, such as a FileNotFoundException or an IOException. If an exception occurs, the program prints an error message to the console.

Source Code

import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
public class Buffered_Reader
{
	public static void main(String args[])
	{
		final String file_name = "file.txt";
		try
		{
			File obj = new File(file_name);
			if (obj.exists() == false)
			{
				System.out.println("File does Not Exist..");
				System.exit(0);
			}
			String text;
			FileReader file_read = new FileReader(obj.getAbsoluteFile());
			BufferedReader buf_read = new BufferedReader(file_read);
 
			//read text from file
			System.out.println("Content of the file is : ");
			while ((text = buf_read.readLine()) != null)
			{
				System.out.println(text);
			}
 
			buf_read.close();
		}
		catch (Exception e)
		{
			System.out.println("Exception : " + e.toString());
		}
	}
}

Output

File does Not Exist..