How do I read a text file?

Date: 2010-09-16. Category: Java I/O examples. Hits: 404K time(s).

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

package org.kodejava.example.io;

import java.io.*;

public class ReadTextFileExample {
    public static void main(String[] args) {
        File file = new File("test.txt");
        StringBuilder contents = new StringBuilder();
        BufferedReader reader = null;

        try {
            reader = new BufferedReader(new FileReader(file));
            String text = null;

            // repeat until all lines is read
            while ((text = reader.readLine()) != null) {
                contents.append(text)
                        .append(System.getProperty(
                                "line.separator"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // show file contents here
        System.out.println(contents.toString());
    }
}

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