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?
Asked
Active
Viewed 169 times
4 Answers
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
- 109,525
- 20
- 134
- 319
1
- Using
java.net.URLopen resource as stream (methodopenStream()). - Load entire as String
- place to your text area
Dewfy
- 23,277
- 13
- 73
- 121
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,917
- 4
- 51
- 70