Java 使用urlconnection下载文件或图片并保存到本地

来源:互联网 发布:播放器 mac 编辑:程序博客网 时间:2024/05/14 17:50
  1. import java.io.FileOutputStream;   
  2. import java.io.InputStream;   
  3. import java.io.OutputStream;   
  4. import java.net.URL;   
  5. import java.net.URLConnection;   
  6.   
  7. /**  
  8.  * 使用URLConnection下载文件或图片并保存到本地。  
  9.  *   
  10.  * @author 老紫竹(laozizhu.com)  
  11.  */  
  12. public class URLConnectionDownloader {   
  13.   
  14.   public static void main(String[] args) throws Exception {   
  15.     download("http://www.laozizhu.com/images/logo.gif""laozizhu.com.gif");   
  16.   }   
  17.   
  18.   /**  
  19.    * 下载文件到本地  
  20.    *   
  21.    * @param urlString  
  22.    *          被下载的文件地址  
  23.    * @param filename  
  24.    *          本地文件名  
  25.    * @throws Exception  
  26.    *           各种异常  
  27.    */  
  28.   public static void download(String urlString, String filename) throws Exception {   
  29.     // 构造URL   
  30.     URL url = new URL(urlString);   
  31.     // 打开连接   
  32.     URLConnection con = url.openConnection();   
  33.     // 输入流   
  34.     InputStream is = con.getInputStream();   
  35.   
  36.     // 1K的数据缓冲   
  37.     byte[] bs = new byte[1024];   
  38.     // 读取到的数据长度   
  39.     int len;   
  40.     // 输出的文件流   
  41.     OutputStream os = new FileOutputStream(filename);   
  42.     // 开始读取   
  43.     while ((len = is.read(bs)) != -1) {   
  44.       os.write(bs, 0, len);   
  45.     }   
  46.     // 完毕,关闭所有链接   
  47.     os.close();   
  48.     is.close();   
  49.   }   
  50. }  
0 0
原创粉丝点击