How do I read text file into JTextArea?

Using the read(Reader in, Object desc) method inherited from the JTextComponent allow us to populate a JTextArea with text content from a file. This example will show you how to do it.

In this example we use an InputStreamReader to read a file from our application resource. You could use other Reader implementation such as the FileReader to read to content of a file. Let’s see the code below.

package org.kodejava.example.swing;

import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import java.io.InputStreamReader;

public class PopulateTextAreaFromFile extends JFrame {
    public PopulateTextAreaFromFile() {
        initialize();
    }

    private void initialize() {
        setSize(300, 300);
        setTitle("Populate JTextArea from File");
        setLayout(new BorderLayout());
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        JTextArea textArea = new JTextArea();
        JScrollPane scrollPane = new JScrollPane(textArea);
        try {
            //
            // Read some text from the resource file to display in
            // the JTextArea.
            //
            textArea.read(new InputStreamReader(
                    getClass().getResourceAsStream("/data.txt")),
                    null);
        } catch (IOException e) {
            e.printStackTrace();
        }

        getContentPane().add(scrollPane, BorderLayout.CENTER);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new PopulateTextAreaFromFile().setVisible(true);
            }
        });
    }
}
Wayan Saryada

Wayan Saryada

A programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, JPA, etc. If you need help on Java programming you can hire me on Fiverr.
Wayan Saryada

Leave a Reply