# Java `BufferedReader`示例

> 原文： [https://howtodoinjava.com/java/io/how-to-read-file-in-java-bufferedreader-example/](https://howtodoinjava.com/java/io/how-to-read-file-in-java-bufferedreader-example/)

如果要使用[`BufferedReader`](https://docs.oracle.com/javase/10/docs/api/java/io/BufferedReader.html)在 Java 中读取文件，请使用以下代码作为模板，并按自己的方式重复使用它。

`BufferedReader`从字符输入流中读取文本，缓冲字符，以便有效读取字符，数组和行。

## 1）使用不带`try-with-resources`的`BufferedReader`（在 Java 7 之前）

```java
package com.howtodoinjava.examples.io;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class BufferedReaderExample 
{
	public static void main(String[] args)
	{
		BufferedReader bufferedReader = null;

		try 
		{

			String currLine;

			bufferedReader = new BufferedReader(new FileReader("C:\\temp\\testOut.txt"));

			while ((currLine = bufferedReader.readLine()) != null)
			{
				System.out.println(currLine);
			}

		}
		catch (IOException e) 
		{
			e.printStackTrace();
		} 
		finally 
		{
			try 
			{
				if (bufferedReader != null)
					bufferedReader.close();
			} 
			catch (IOException ex) 
			{
				ex.printStackTrace();
			}
		}
	}
}

```

## 2）将`BufferedReader`与`try-with-resources`一起使用（Java 7 及更高版本）

```java
package com.howtodoinjava.examples.io;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class BufferedReaderExample 
{
	public static void main(String[] args)
	{
		try (BufferedReader bufferedReader = new BufferedReader(new FileReader("C:\\temp\\testOut.txt")))
		{

			String currLine;

			while ((currLine = bufferedReader.readLine()) != null) 
			{
				System.out.println(currLine);
			}

		} 
		catch (IOException e) 
		{
			e.printStackTrace();
		}
	}
}

```

 **祝您学习愉快！**