o_oand0_0

软件开发
随笔 - 4, 文章 - 2, 评论 - 5, 引用 - 0
数据加载中……

Java下载指定url的资源到指定路径

import java.net.*;
import java.io.*;

 1public void downLoadFile(String srcUri, String destPath) {
 2        FileOutputStream fos = null;
 3        BufferedInputStream bis = null;
 4        HttpURLConnection httpUrl = null;
 5        URL url = null;
 6        int bsize = 1024;
 7
 8        byte[] buf = new byte[bsize];
 9        int size = 0;
10        try {
11            url = new URL(srcUri);
12            httpUrl = (HttpURLConnection) url.openConnection();
13            httpUrl.connect();
14            bis = new BufferedInputStream(httpUrl.getInputStream());
15
16            fos = new FileOutputStream(destPath);
17            while ((size = bis.read(buf)) != -1{
18                fos.write(buf, 0, size);
19            }

20            fos.flush();
21        }
 catch (IOException e) {
22        }
 catch (ClassCastException e) {
23        }
 finally {
24            try {
25                fos.close();
26                bis.close();
27                httpUrl.disconnect();
28            }
 catch (IOException e) {
29            }
 catch (NullPointerException e) {
30            }

31        }

32    }

测试:

downLoadFile("http://www.baidu.com/img/baidu_sylogo1.gif","c:\\baidu_sylogo1.gif");


 

posted on 2011-10-21 16:17 o_oand0_0 阅读(431) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航: