package download;import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.net.URLConnection; import java.util.zip.GZIPInputStream;/*** 从url指定的地址下载一个文件到本地* 2014-8-5 17:28:50**/ public class Downloader{private URL url;// 网络文件的地址URLConnection con;// 到URL的连接InputStream is;// 输入流public Downloader(String urlStr,String path,String fileName) throws Exception{url = new URL(urlStr);con = url.openConnection();is = con.getInputStream();// 未取到文件int length=con.getContentLength();if(length==71495){throw new Exception(urlStr+"指向的文件不存在.");}File folder=new File(path);if(folder.exists()==false || folder.isFile()){folder.mkdir();}String filename=path+File.separator+fileName;String code = con.getHeaderField("Content-Encoding");if ((null != code) && code.equals("gzip")) {GZIPInputStream gis = new GZIPInputStream(is);// 1K的数据缓冲byte[] bs = new byte[1024];// 读取到的数据长度int len;// 输出的文件流OutputStream os = new FileOutputStream(filename);// 开始读取while ((len = gis.read(bs)) != -1) {os.write(bs, 0, len);}// 完毕,关闭所有链接 gis.close();os.close();is.close();} else {// 1K的数据缓冲byte[] bs = new byte[1024];// 读取到的数据长度int len;// 输出的文件流OutputStream os = new FileOutputStream(filename);// 开始读取while ((len = is.read(bs)) != -1) {os.write(bs, 0, len);}// 完毕,关闭所有链接 os.close();is.close();}System.out.println(filename+"已保存");}public static void main(String[] args) throws Exception{String picUrl="http://img.1234.com/Upload2010/Sabfdra/SabrafdsfsfCOVERGIRLgtz/01.jpg";String[] arr=picUrl.split("/");int n=arr.length;String folder="C://reedf//wallpaper//"+arr[n-2];String[] arr2=arr[n-1].split("[.]");String ext=arr2[arr2.length-1];picUrl=picUrl.replace(arr[n-1], "");String url;String filename;String index;for(int i=0;i<150;i++){if(i<10){index="0"+i;}else{index=String.valueOf(i);}url=picUrl+index+"."+ext;filename=index+"."+ext;try{new Downloader(url,folder,filename);}catch(Exception ex){// do nothing }}} }
本文转自张昺华-sky博客园博客,原文链接:http://www.cnblogs.com/xiandedanteng/p/3892771.html,如需转载请自行联系原作者
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态