1.完整代码
public static void httpFileDownload(){
String url = "http://a3.att.hudong.com/68/61/300000839764127060614318218_950.jpg";
try {
URL url2 = new URL(url);
//获取http连接
HttpURLConnection connection = (HttpURLConnection) url2.openConnection();
int length = connection.getContentLength();
System.out.println("文件size:" + length);
connection.setConnectTimeout(3 * 1000);
//connection .setRequestProperty("Accept-Encoding", "identity");
//根据链接获取数据流
InputStream stream = connection.getInputStream();
// int available = stream.available();
FileOutputStream out = new FileOutputStream(new File("F://data//cc.jpg"));
//缓冲数组
byte[] data = new byte[1024];
int len=0;
while((len=stream.read(data))!= -1){
System.out.println(len);
out.write(data,0,len);
}
stream.close();
out.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
2.InputStream中read(byte[] b)方法详解
read(byte[] b) :
-
从输入流中读取一定数量的字节,并将其存储在缓冲区数组 b 中。以整数形式返回实际读取的字节数。在输入数据可用、检测到文件末尾或者抛出异常前,此方法一直阻塞。
-
如果 b 的长度为 0,则不读取任何字节并返回 0;否则,尝试读取至少一个字节。如果因为流位于文件末尾而没有可用的字节,则返回值
-1;否则,至少读取一个字节并将其存储在 b 中。 -
将读取的第一个字节存储在元素 b[0] 中,下一个存储在 b[1] 中,依次类推。读取的字节数最多等于b 的长度。设 k
为实际读取的字节数;这些字节将存储在 b[0] 到 b[k-1] 的元素中,不影响 b[k] 到b[b.length-1] 的元素。