从URL读取XML作为字符串

时间:2011-07-14 13:46:41

标签: java xml string

我的文件为https://localhost/myeg.xml 我想在Java中将该文件读为字符串。 如果有一个单独的图书馆或其他任何方式,有人可以帮助我。

3 个答案:

答案 0 :(得分:8)

您可以尝试:

URL url = new URL(myfile);
InputStream is = url.openStream();
byte[] buf = new byte[1024];
int read = -1;
StringBuilder bld = new StringBuilder();
while ((read = is.read(buf, 0, buf.length) != -1) {
  bld.append(new String(buf, 0, read, "utf-8"));
}

String s = bld.toString();
  • 假设utf-8,如果发起主机确实指定了编码,我会使用.openConnection()并在读取流之前找出“内容类型”(和编码)。
  • 为了表现,您可能希望将InputStream包裹在BufferedInputStream
  • 您可能希望try-finally关闭InputStream

答案 1 :(得分:4)

common-io

URL url = new URL("https://etc..");
InputStream input = url.openStream();
String str = IOUtils.toString(input, "utf-8"); //encoding is important
input.close(); // this is simplified - resource handling includes try//finally

或者查看the official tutorial中的示例。

答案 2 :(得分:2)

您可以使用Commons HTTP Client。见this example