How do I read a text file using BufferedReader?

The code snippet below is an example of how to read a text file using BufferedReader from the package. This snippet read a text file called test.txt and print out its content.

To create an instance of we do the following steps:

File file = new File("test.txt");
FileReader fileReader = new FileReader(file));
BufferedReader bufferedReader = new BufferedReader(fileReader);

Let’s see the complete code snippet.



public class ReadTextFileExample {
    private static String lineSeparator = System.getProperty("line.separator");

    public static void main(String[] args) {
        File file = new File("test.txt");
        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            StringBuilder contents = new StringBuilder();
            String text;
            while ((text = reader.readLine()) != null) {

        } catch (IOException e) {

You can also try to use the following example to read a file, How do I read text file content line by line using commons-io?. To create and write a text file see the following example: How do I create and write data into text file?.