原文地址:
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 args13 * @throws Exception 14 */15 public static void main(String[] args) throws Exception {16 // TODO Auto-generated method stub17 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 // 构造URL22 URL url = new URL(urlString);23 // 打开连接24 URLConnection con = url.openConnection();25 //设置请求超时为5s26 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 }