Java BufferedReader close() Method
Example
Read a line from a file, then close the reader:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
FileWriter myWriter = new FileWriter("filename.txt");
myWriter.write("Hello World");
myWriter.close();
BufferedReader br = new BufferedReader(new FileReader("filename.txt"));
System.out.println(br.readLine());
br.close();
}
}
Definition and Usage
The close() method closes the reader. It also closes the reader inside it (here the FileReader), so the file is released (other programs can use it again).
After you close a reader, you cannot read from it anymore. Methods like read() and readLine() then throw an IOException.
Tip: Use try-with-resources to close the reader automatically, even if an error occurs.
Syntax
public void close()
Parameter Values
None.
Related Pages
❮ BufferedReader Methods