1. package org.sce.web; 
  2. import java.io.BufferedInputStream; 
  3. import java.io.FileOutputStream; 
  4. import java.io.IOException; 
  5. import java.net.HttpURLConnection; 
  6. import java.net.URL; 
  7.  
  8. public class Download implements Runnable { 
  9.  
  10.     private static final int BUFFER_SIZE = 4096
  11.     private String destUrl; 
  12.     private String fileName; 
  13.  
  14.     public Download(String destUrl, String fileName) { 
  15.         this.destUrl = destUrl; 
  16.         int i = destUrl.lastIndexOf("/"); 
  17.         this.fileName = fileName + destUrl.substring(i + 1); 
  18.     } 
  19.  
  20.     public void run() { 
  21.         try { 
  22.             saveToFile(destUrl, fileName); 
  23.             System.out.println("download done,saved as: " + fileName); 
  24.         } catch (IOException e) { 
  25.             System.out.println("downloading error: " + e.getMessage()); 
  26.         } 
  27.     } 
  28.  
  29.     public void saveToFile(String destUrl, String fileName) throws IOException { 
  30.         FileOutputStream fos = null
  31.         BufferedInputStream bis = null
  32.         HttpURLConnection httpconn = null
  33.         URL url = null
  34.         byte[] buf = new byte[BUFFER_SIZE]; 
  35.         int size = 0
  36.  
  37.         // create connection 
  38.         url = new URL(destUrl); 
  39.         httpconn = (HttpURLConnection) url.openConnection(); 
  40.         // connect the resource 
  41.         httpconn.connect(); 
  42.         // get BufferedInputStream 
  43.         bis = new BufferedInputStream(httpconn.getInputStream()); 
  44.         // create FileOutputStream for file 
  45.         fos = new FileOutputStream(fileName); 
  46.  
  47.         System.out.println("connecting " + destUrl + "..."); 
  48.  
  49.         //save file 
  50.         while ((size = bis.read(buf)) != -1
  51.             fos.write(buf, 0, size); 
  52.         fos.close(); 
  53.         bis.close(); 
  54.         httpconn.disconnect(); 
  55.     } 
  56.  
  57.     public static void main(String[] args) { 
  58.         String url="http://www.cxybl.com/templets/default/p_w_picpaths/logo1.gif"
  59.         String path="D:/download/"
  60.         Download  d=new Download(url,path); 
  61.         Thread th = new Thread(d); 
  62.         th.start(); 
  63.     } 
  64. }

原文地址:http://www.cxybl.com/html/bcyy/java/201108252500.html