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 the content of a file. Let’s see the code below.

package org.kodejava.swing;

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

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

    public static void showFrame() {
        JPanel panel = new PopulateTextAreaFromFile();
        panel.setOpaque(true);

        JFrame frame = new JFrame("Populate JTextArea from File");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setContentPane(panel);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(PopulateTextAreaFromFile::showFrame);
    }

    private void initialize() {
        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(Objects.requireNonNull(
                    getClass().getResourceAsStream("/data.txt"))), null);
        } catch (IOException e) {
            e.printStackTrace();
        }

        this.setPreferredSize(new Dimension(500, 200));
        this.setLayout(new BorderLayout());
        this.add(scrollPane, BorderLayout.CENTER);
    }
}

The output of the code snippet above is:

Read Text File into JTextArea

How do I create a URL object?

package org.kodejava.net;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class URLDemo {
    public static void main(String[] args) {
        try {
            // Creating a url object by specifying each parameter separately, including
            // the protocol, hostname, port number, and the page name
            URL url = new URL("https", "kodejava.org", 443, "/index.php");

            // We can also specify the address in a single line
            url = new URL("https://kodejava.org:443/index.php");

            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(url.openStream(), StandardCharsets.UTF_8));

            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}