PUBLISHED ON: MARCH 8, 2021
Java BufferedReader close() Method
In this tutorial, we will learn about the close() method of BufferedReader class in Java. This method is used to close this BufferedReader
stream and free all other system resources linked with this stream. It is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
Syntax
This is the syntax declaration of a close() method, this method does not accept any parameter and does not return any parameter.
public void close() throws IOException
Example 1: Close BufferedReader Instance
In this example, we are going to implement the close() method, firstly we read the required data from the file, once the data is read successfully then we call the close() method to close the BufferedReaader stream from which we read the data, it will free all other system resources linked with this stream.
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);
}
fileReader.close();
bufferReader.close();
}
}
Hello Studytonight
output.txt
Hello Studytonight
Example 1: Close FileReader Instance
Here, we have created the BufferedReader
after that we read the data using the readLine()
method and then we call close() method to free up all the system resources associated with it.
import java.io.BufferedReader;
import java.io.FileReader;
class StudyTonight
{
public static void main(String[] args)
{
try
{
FileReader fileReader = new FileReader("E://studytonight//output.txt");
BufferedReader buffReader = new BufferedReader(fileReader);
System.out.println(buffReader.readLine());
fileReader.close();
buffReader.close();
}
catch(Exception e)
{
System.out.println("Error: "+e.toString());
}
}
}
ABC
output.txt
ABC
Conclusion
In this tutorial, we learned about a close() method of BufferedReader class in Java. his method is used to close this BufferedReader
stream and free all other system resources linked with this stream. It is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.