Reading File Content using FileReader Java Program Example

Reading File Content using FileReader Java

In this tutorial, I am sharing the simple program about Reading File Content using FileReader Java. The example program has been tested and output is shared in the same post.

FileReaderExample.java

package com.dineshkrish.files;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class FileReaderExample {

	public static void main(String[] args) throws IOException {

		// Defining the File Object for Input File to read
		File inputFile = new File("abc.txt");

		// Reader Object
		FileReader fr = null;
		try {

			fr = new FileReader(inputFile);

			// Reading the first Character
			int data = fr.read();

			// Reading each character until reach last character in file
			while (data != -1) {

				System.out.print((char) data); // will return integer
												// value(ASCII) will be
												// converted as character

				data = fr.read();
			}

		} catch (FileNotFoundException ex) {

			System.out.println(ex.getMessage());
			ex.printStackTrace();
		} catch (IOException ex) {

			System.out.println(ex.getMessage());
			ex.printStackTrace();
		} finally {

			// Closing the resources after the IO Operation
			fr.close();
		}

	}
}

Input File Content(ie: abc.txt)

Reading File Content using FileReader

Output

—————-
Hello everyone,

This is the sample program to read file using FileReader class in Java.

———
Regards,
Dinesh Krishnan

Hello, folks, I am a founder of dineshkrish.com. I love Java and Open source technologies, If you find my tutorials are useful, please consider making donations to these charities.