Read from a URL and dump the string to a text area - Java Swing

Java examples for Swing:JTextArea

Description

Read from a URL and dump the string to a text area

Demo Code

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class Main extends JFrame {
  JTextArea box = new JTextArea("Getting data ...");

  public Main() {
    super("Get File Application");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(600, 300);/* w w w .j  ava  2  s . c om*/
    JScrollPane pane = new JScrollPane(box);
    add(pane);
    setVisible(true);
  }

  void getData() throws MalformedURLException {
    URL page = new URL("https://java2s.com");
    StringBuilder text = new StringBuilder();
    try {
      HttpURLConnection conn = (HttpURLConnection) page.openConnection();
      conn.connect();
      InputStreamReader in = new InputStreamReader(
          (InputStream) conn.getContent());
      BufferedReader buff = new BufferedReader(in);
      box.setText("Getting data ...");
      String line;
      do {
        line = buff.readLine();
        text.append(line);
        text.append("\n");
      } while (line != null);
      box.setText(text.toString());
    } catch (IOException ioe) {
      System.out.println("IO Error:" + ioe.getMessage());
    }
  }

  public static void main(String[] arguments)throws MalformedURLException {
      Main app = new Main();
      app.getData();
  }
}

Related Tutorials