我的文件为https://localhost/myeg.xml 我想在Java中将该文件读为字符串。 如果有一个单独的图书馆或其他任何方式,有人可以帮助我。
答案 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)
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!