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

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

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

 1 public   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 " );


 

你可能感兴趣的:(Java下载指定url的资源到指定路径)