如何通过网络加载文件并将其作为字符串处理 [英] How to load a file across the network and handle it as a String

查看:69
本文介绍了如何通过网络加载文件并将其作为字符串处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在JTextArea中显示URL的内容.我有一个指向XML文件的URL,我只想在JTextArea中显示文件的内容.我该怎么办?

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?

推荐答案

您可以这样做:

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();

然后,文件的内容存储在名为yourFileAsAStringString中.

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

您可以使用JTextArea中. lang.String,%20int%29"rel =" nofollow> JTextArea.insert(yourFileAsAString,pos)或使用JTextArea.append(yourFileAsAString)附加. 在后一种情况下,您可以直接将读取的文本附加到JTextArea,而不是使用StringBuilder.为此,只需从上面的代码中删除StringBuilder并按以下方式修改for()循环:

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

这篇关于如何通过网络加载文件并将其作为字符串处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆