簡體   English   中英

從 URL 中讀取 XML 作為字符串

[英]Read XML from URL as a string

我有一個文件為https://localhost/myeg.xml我想在 Java 中將文件作為字符串讀取。 如果有單獨的圖書館或其他方式,有人可以幫助我。

你可以試試:

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()並在讀取 stream 之前找出“內容類型”(和編碼)。
  • 為了提高性能,您可能希望將InputStream包裝在BufferedInputStream中。
  • 你可能想要一個try-finally來關閉InputStream

常見的 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

或者看官方教程中的例子。

您可以使用Commons HTTP Client 這個例子

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM