Java中的 BufferedReader close() 方法及示例
Java中BufferedReader类的close()方法用于关闭流并释放所有与流操作相关的系统资源。
句法:
public void close()
throws IOException
参数:此方法不接受任何参数。
返回值:此方法不返回任何值。
异常:如果发生 I/O 错误,此方法将抛出IOException 。
下面的程序说明了 IO 包中 BufferedReader 类中的 close() 方法:
程序1:假设文件“c:/demo.txt”存在。
// Java program to illustrate
// BufferedReader close() method
import java.io.*;
public class GFG {
public static void main(String[] args)
throws IOException
{
// Read stream file 'demo.txt'
// containing text "GEEKSFORGEEKS"
FileReader fileReader
= new FileReader(
"c:/demo.txt");
// Convert fileReader to
// bufferedReader
BufferedReader buffReader
= new BufferedReader(
fileReader);
// Call read() method
while (buffReader.ready()) {
System.out.print(
(char)buffReader.read());
}
// Call close() method
buffReader.close();
}
}
输入:
输出:
程序2:假设文件“c:/demo.txt”存在。
// Java program to illustrate
// BufferedReader close() method
import java.io.*;
public class GFG {
public static void main(String[] args)
throws IOException
{
try {
// Read stream file 'demo.txt'
// containing text "GEEKSFORGEEKS"
FileReader fileReader
= new FileReader(
"c:/demo.txt");
// Convert fileReader to
// bufferedReader
BufferedReader buffReader
= new BufferedReader(
fileReader);
// Call close() method
buffReader.close();
// Call read() method
System.out.print(
(char)buffReader.read());
}
catch (IOException e) {
// Exception is thrown
System.out.println(
"BufferedReader is closed");
}
}
}
输入:
输出:
参考: https: Java/io/BufferedReader.html#close()