public class DownloadImg {
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 = "图片保存位置"+fileName;
// 构造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();
}
}
根据图片url批量下载图片
最新推荐文章于 2024-07-22 13:45:39 发布