今天,在逛站时,发现了许多好看的图片,想将其下载下来。一张一张另存为就太low,当然也可以采用工具的方式,将一堆链接放到里面,批量下载。但图片链接有规律可循的话,使用代码的方式更合适些。
在参考了别人的代码后,实现了如下功能:
java代码:
import com.github.pagehelper.util.StringUtil;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class DownloadImg {
public static void main(String[] args) {
List<String> urls=new ArrayList<String>();
for(int i=0;i<606;i++){
urls.add("http://blog.api.xiaoyou66.com/assets/images/background/img"+i+".jpg");
}
Map<String ,Object> map = new HashMap<String,Object>();
map.put("fileName","");
map.put("urls",urls);
DownloadImg img=new DownloadImg();
img.download(map);
}
public void download(Map<String ,Object> map){
List<String> urls = (List<String>) map.get("urls");
String fileName = (String) map.get("fileName");
for (String imgUrl : urls) {
if (StringUtil.isEmpty(imgUrl)){
continue;
}
System.out.println(imgUrl);
System.out.println();
try {
String filename = imgUrl.substring(imgUrl.lastIndexOf("/"));
String savePath = "D://壁纸/";
// 构造URL
URL url = new URL(imgUrl);
// 打开连接
URLConnection con = url.openConnection();
con.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko");
//设置请求超时为5s
con.setConnectTimeout(5*1000);
// 输入流
InputStream is = con.getInputStream();
// 1K的数据缓冲
byte[] bs = new byte[1024];
// 读取到的数据长度
int len;
// 输出的文件流
File sf=new File(savePath);
if(!sf.exists()){
sf.mkdirs();
}
long length = (sf.length())/128;
OutputStream os = new FileOutputStream(sf.getPath()+"/"+filename);
// 开始读取
while ((len = is.read(bs)) != -1) {
os.write(bs, 0, len);
}
// 完毕,关闭所有链接
os.close();
is.close();
}catch (Exception e){
e.printStackTrace();
//urls.add(imgUrl);
continue;
}
}
System.out.println("===================end====================");
}
private static byte[] readInputStream(InputStream inputStream) throws IOException {
byte[] buffer = new byte[1024];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while((len = inputStream.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
bos.close();
return bos.toByteArray();
}
}



还没有评论,来说两句吧...