How to load a file across the network and handle it as a String

社会主义新天地 提交于 2019-12-13 19:04:09

问题


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


来源:https://stackoverflow.com/questions/7158854/how-to-load-a-file-across-the-network-and-handle-it-as-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!