How do I read a text file?

The code snippet below is an example of how to read a text file. This program will read a file called test.txt and shows its content.



public class ReadTextFileExample {
    public static void main(String[] args) {
        File file = new File("/Users/wsaryada/kodejava/test.txt");

        try (BufferedReader reader =
                     new BufferedReader(new FileReader(file))) {
            StringBuilder contents = new StringBuilder();

            String text = null;
            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?.

Wayan Saryada

I am a programmer, a runner, an open water diver and currently living in the island of Bali, Indonesia. If you need help on Java programming you can hire me on Fiverr.

Leave a Comment.