BufferReader读取文件
时间: 2023-08-29 17:10:38 浏览: 85
BufferedReader是一个用于读取字符流的缓冲输入流。它可以提高读取文件的效率。通常情况下,每次读取请求都会导致底层字符或字节流发出相应的读取请求。因此,建议将BufferedReader与代价较高的读取操作的Reader(如FileReader和InputStreamReader)一起使用。例如,可以使用以下代码来读取文件:
```java
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader("file.txt"));
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bufferedReader != null) {
bufferedReader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
```
在上述代码中,我们创建了一个BufferedReader对象,并将其包装在FileReader中,以便读取指定文件的内容。如果没有缓冲,每次调用readLine()方法都会导致从文件中读取字节,将其转换为字符,然后返回,这可能非常低效。而使用BufferedReader可以提高读取文件的效率。\[1\]\[2\]\[3\]
#### 引用[.reference_title]
- *1* [BufferReader的用法](https://blog.csdn.net/u010974598/article/details/19325483)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down1,239^v3^insert_chatgpt"}} ] [.reference_item]
- *2* *3* [Java - BufferedReader读文件](https://blog.csdn.net/m0_53753920/article/details/130179122)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down1,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
阅读全文