How to load a file across the network and handle i

2019-07-30 19:29发布

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?

4条回答
The star\"
2楼-- · 2019-07-30 19:58
  1. Using java.net.URL open resource as stream (method openStream()).
  2. Load entire as String
  3. place to your text area
查看更多
别忘想泡老子
3楼-- · 2019-07-30 20:06

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

查看更多
老娘就宠你
4楼-- · 2019-07-30 20:10

Assuming its HTTP URL

Open the HTTPURLConnection and read out the content

查看更多
放荡不羁爱自由
5楼-- · 2019-07-30 20:19

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));
}
查看更多
登录 后发表回答