2011-07-14 42 views

回答

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

这是一个'InputStream'。他说他想要'String'。完成示例;) – Bozho

+1

的确如此。我改变:) –

+0

非常感谢你...... – theshadowmonkey

2

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

+1

这对于一个简单的任务来说是巨大的.. – Bozho

+2

等待'直到你发现你需要验证和头部操作来获取文件! ;) – Vlad

+1

一个接一个。你不能把所有的东西都扔到对这个主题不太了解的人身上 – Bozho

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

+0

谢谢你....我使用了上面的答案,因为它有更少的utils被导入 – theshadowmonkey