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
}
}
}
}
爪哇国新游记之二十八----从url指定的地址下载文件到本地的相关教程结束。