dsa

Java FileReader

In this tutorial, we will learn about the Java FileReader, its constructors and its methods with the help of an example.

This is a Convenience class for reading character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are appropriate. To specify these values yourself, construct an InputStreamReader on a FileInputStream.

Constructors of FileReader

  • FileReader(File file) :Creates a new FileReader, given the File to read from.
  • FileReader(FileDescriptor fd) :Creates a new FileReader, given the FileDescriptor to read from.
  • FileReader(String fileName) :Creates a new FileReader, given the name of the file to read from.

Methods

Methods inherited from class java.io.InputStreamReader


close, getEncoding, read, ready

Methods inherited from class java.io.Reader


mark, markSupported, read, reset, skip

Examples :

Suppose we have a file named input.txt with the following content.


This file consists of a single line.

import java.io.FileReader;

class Codemistic 
{
 	public static void main(String[] args) 
	{

    		// Creates an array of character
    		char[] array = new char[100];

    		try 
		{
      			// Creates a reader using the FileReader
      			FileReader input = new FileReader("input.txt");

      			// Reads characters
      			input.read(array);
      			System.out.println("Data in the file: ");
      			System.out.println(array);

      			// Closes the reader
      			input.close();
    		}
    		catch(Exception e) 
		{
      			e.getStackTrace();
    		}
  	}
}


Output :

Data in the file:
This file consists of a single line.