How to load a file across the network and handle i

2019-07-30 19:38发布

问题:

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?

回答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));
}


回答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



回答3:

Assuming its HTTP URL

Open the HTTPURLConnection and read out the content



回答4:

  1. Using java.net.URL open resource as stream (method openStream()).
  2. Load entire as String
  3. place to your text area