使用 try-finally 块来确保缓冲区中的字符被正确刷新。示例如下:
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader("file.txt"));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
在该示例中,我们使用了 try-finally 块来关闭 reader,并确保缓冲区中的字符被正确刷新。这样可以避免出现缓冲区内容丢失的情况。