PUBLISHED ON: MARCH 1, 2021
Java BufferedReader read() Method
In this tutorial, we will learn about read()
method of BufferedReader class in Java. The task of this method is to read a single character from the given buffered reader. This read()
method reads one character at a time from the buffered stream and returns it as an integer value.
Syntax
This method returns the character that is read by this method in the form of an integer. If the end of the stream has been reached the method returns -1.
public int read() throws IOException
Example 1
In this example, we are implementing the read() of BufferedReader class to read the data from the source, here we created the FileReader and connected it to the BufferedReader then we check whether the buffered reader is ready or not by calling the method ready() method once the buffer is ready we print until it reaches at the end of file.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
class StudyTonight
{
public static void main(String[] args) throws IOException
{
FileReader fileReader = new FileReader("E://studytonight//output.txt");
BufferedReader buffReader = new BufferedReader(fileReader);
while (buffReader.ready())
{
char c = (char)buffReader.read();
System.out.print(c);
}
}
}
Hello studytonight
output.txt
Hello studytonight
Example 2
import java.io.BufferedReader;
import java.io.FileReader;
public class StudyTonight
{
public static void main(String args[])
{
try
{
FileReader fileReader=new FileReader("E:\\studytonight\\output.txt");
BufferedReader br=new BufferedReader(fileReader);
int i;
while((i=br.read())!=-1){
System.out.print((char)i);
}
br.close();
fileReader.close();
}
catch(Exception e)
{
System.out.print(false);
}
}
}
This is a text.
output.txt
This is a text.
Conclusion
In this tutorial, we learned about read()
method of BufferedReader class in Java, which reads a single character from the given buffered reader and returns it as an integer value.