[转]java 下载网络上的图片并保存到本地目录

原文地址:http://takeme.iteye.com/blog/1683380

 1 import java.io.File;
 2 import java.io.FileOutputStream;
 3 import java.io.InputStream;
 4 import java.io.OutputStream;
 5 import java.net.URL;
 6 import java.net.URLConnection;
 7 
 8 
 9 public class DownloadImage {
10 
11     /**
12      * @param args
13      * @throws Exception 
14      */
15     public static void main(String[] args) throws Exception {
16         // TODO Auto-generated method stub
17          download("http://ui.51bi.com/opt/siteimg/images/fanbei0923/Mid_07.jpg", "51bi.gif","c:\\image\\");
18     }
19     
20     public static void download(String urlString, String filename,String savePath) throws Exception {
21         // 构造URL
22         URL url = new URL(urlString);
23         // 打开连接
24         URLConnection con = url.openConnection();
25         //设置请求超时为5s
26         con.setConnectTimeout(5*1000);
27         // 输入流
28         InputStream is = con.getInputStream();
29     
30         // 1K的数据缓冲
31         byte[] bs = new byte[1024];
32         // 读取到的数据长度
33         int len;
34         // 输出的文件流
35        File sf=new File(savePath);
36        if(!sf.exists()){
37            sf.mkdirs();
38        }
39        OutputStream os = new FileOutputStream(sf.getPath()+"\\"+filename);
40         // 开始读取
41         while ((len = is.read(bs)) != -1) {
42           os.write(bs, 0, len);
43         }
44         // 完毕,关闭所有链接
45         os.close();
46         is.close();
47     } 
48 
49 }

 

posted @ 2017-08-25 16:19  dirgo  阅读(950)  评论(0编辑  收藏  举报