Signup/Sign In

Java FileReader read() Method

In this tutorial, we will learn about the read() method of FileReader class in Java. This method is used to read and return a single character, in the form of an integer value that contains the char value of the character read.

Syntax

This method returns the character read as an integer in the range 0 to 65535. If it returns -1 as an int value, all the data has been read and FileReader can be closed.

public abstract int read()

Example 1: Read using FileReader

In this example, 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.

import java.io.FileReader;
public class StudyTonight 
{
	public static void main(String args[])
	{
		try
		{   		
			FileReader fileReader=new FileReader("E:\\studytonight\\output.txt");    
			char c=(char) fileReader.read();
			System.out.print(c);    
			fileReader.close();    
		}
		catch(Exception e)
		{
			System.out.println("Error: "+e.toString());
		}
	}
}


S

output.txt

Studytonight

Example 2: Read Using FileReader

In the following example, we are reading the data from the file. Firstly we created a FileReader after that using the read() method we are reading each character and print it on the console.

import java.io.FileReader;
public class StudyTonight 
{
	public static void main(String args[])
	{
		try
		{   		
			FileReader fileReader=new FileReader("E:\\studytonight\\output.txt");    
			int i;    
			while((i=fileReader.read())!=-1)    
				System.out.print((char)i);    
			fileReader.close();    
		}
		catch(Exception e)
		{
			System.out.println("Error: "+e.toString());
		}
	}
}

Welcome to Studytonight

output.txt

Welcome to Studytonight

Conclusion

In this tutorial, we learned about the read() method of FileReader class in Java, which is used to read a single character and return it in the form of an integer value, in the range of 0 to 65535 and returns -1 if the end of the stream has been reached.



About the author:
I am the founder of Studytonight. I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development.