Skip to content
Related Articles

Related Articles

Java FileReader Class read() Method with Examples

Improve Article
Save Article
  • Last Updated : 16 Feb, 2022
Improve Article
Save Article

The read() method of FileReader class in Java is used to read and return a single character in the form of an integer value that contains the character’s char value. The character read as an integer in the range of 0 to 65535 is returned by this function. If it returns -1 as an int number, it means that all of the data has been read and that FileReader may be closed.

Syntax:

public abstract int read()

Returns: The read() method returns a single character in the form of an integer value that contains the character’s char value. It returns -1 when all of the data has been read and that FileReader may be closed.

Example 1: We are calling the read() method of FileReader class to read the data from the file, this method reads the one character at a time and returns its ASCII value in the integer format. To print the actual data we must typecast it to the char.

Java




// Java Program to demonstrate the use of read() 
// method of FileReader class in Java
  
import java.io.FileReader;
  
public class GFG {
    public static void main(String args[])
    {
        try {
            FileReader fileReader = new FileReader(
                "C:\\Users\\lenovo\\Desktop\\input.txt");
            char c = (char)fileReader.read();
            System.out.print(c);
            fileReader.close();
        }
        catch (Exception e) {
            System.out.println("Error: " + e.toString());
        }
    }
}


The input.txt file has the following content:

Output:

Example 2:

Java




// Java Program to demonstrate the use of read() 
// method of FileReader class in Java
  
import java.io.FileReader;
  
public class GFG {
    public static void main(String args[])
    {
        try {
            FileReader fileReader = new FileReader(
                "C:\\Users\\lenovo\\Desktop\\input.txt");
            int i;
            while ((i = fileReader.read()) != -1)
                System.out.print((char)i);
            fileReader.close();
        }
        catch (Exception e) {
            System.out.println("Error: " + e.toString());
        }
    }
}


After creating a FileReader, we read each character and report it to the console using the read() function.

Output:


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!