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 java.io package. This snippet read a text file called test.txt and print out its content.

To create an instance of java.io.BufferedReader 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.

package org.kodejava.example.io;

import java.io.*;

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) {
                contents.append(text).append(lineSeparator);
            }

            System.out.println(contents.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

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?.

Wayan Saryada

Programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply