1

I would like to display the contents of the url in a JTextArea. I have a url that points to an XML file, I just want to display the contents of the file in JTextArea. how can I do this?

Shlublu
  • 10,527
  • 4
  • 50
  • 68
CLUEL3SS
  • 225
  • 1
  • 3
  • 10
  • 1
    possible duplicate of [How to send HTTP request in java?](http://stackoverflow.com/questions/1359689/how-to-send-http-request-in-java) – Thilo Aug 23 '11 at 09:31

4 Answers4

2

better JComponent for Html contents would be JEditorPane/JTextPane, then majority of WebSites should be displayed correctly there, or you can create own Html contents, but today Java6 supporting Html <=Html 3.2, lots of examples on this forum or here

mKorbel
  • 108,320
  • 17
  • 126
  • 296
1

Assuming its HTTP URL

Open the HTTPURLConnection and read out the content

jmj
  • 225,392
  • 41
  • 383
  • 426
1
  1. Using java.net.URL open resource as stream (method openStream()).
  2. Load entire as String
  3. place to your text area
Dewfy
  • 21,895
  • 12
  • 66
  • 114
1

You can do that way:

final URL myUrl= new URL("http://www.example.com/file.xml");
final InputStream in= myUrl.openStream();

final StringBuilder out = new StringBuilder();
final byte[] buffer = new byte[BUFFER_SIZE_WHY_NOT_1024];

try {
   for (int ctr; (ctr = in.read(buffer)) != -1;) {
       out.append(new String(buffer, 0, ctr));
   }
} catch (IOException e) {
   // you may want to handle the Exception. Here this is just an example:
   throw new RuntimeException("Cannot convert stream to string", e);
}

final String yourFileAsAString = out.toString();

Then the content of your file is stored in the String called yourFileAsAString.

You can insert it in your JTextArea using JTextArea.insert(yourFileAsAString, pos) or append it using JTextArea.append(yourFileAsAString). In this last case, you can directly append the readed text to the JTextArea instead of using a StringBuilder. To do so, just remove the StringBuilder from the code above and modify the for() loop the following way:

for (int ctr; (ctr = in.read(buffer)) != -1;) {
    youJTextArea.append(new String(buffer, 0, ctr));
}
Shlublu
  • 10,527
  • 4
  • 50
  • 68