爪哇国新游记之二十八----从url指定的地址下载文件到本地

 2023-09-05 阅读 369 评论 0

摘要: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指定的地址下载一个文件到本地
复制代码
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,如需转载请自行联系原作者


版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/1/267.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息