博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java读流方式,下载网络上的图片
阅读量:4677 次
发布时间:2019-06-09

本文共 1693 字,大约阅读时间需要 5 分钟。

本工具类支持url的list集合,具体实现如下所示:

public static void download(ArrayList
listUrl, String downloadPath) { for (String url : listUrl) { try { getImageFromNetByUrl(url,downloadPath); } catch (Exception e) { e.printStackTrace(); } } } public static void getImageFromNetByUrl(String strUrl,String path) throws Exception { String imageName = strUrl.substring(strUrl.lastIndexOf("/") + 1, strUrl.length()); _FakeX509TrustManager.allowAllSSL(); URL url = new URL(strUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // conn.setRequestMethod("GET"); conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); conn.setConnectTimeout(5 * 1000); InputStream inStream = conn.getInputStream();// 通过输入流获取图片数据 byte[] btImg = readInputStream(inStream);// 得到图片的二进制数据 inStream.close(); conn.disconnect(); try { File file = new File(path+imageName); DirectoryUtil.createFile(path+imageName); FileOutputStream fops = new FileOutputStream(file); fops.write(btImg); fops.flush(); fops.close(); } catch (Exception e) { e.printStackTrace(); } } public static byte[] readInputStream(InputStream inStream) throws Exception { ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while ((len = inStream.read(buffer)) != -1) { outStream.write(buffer, 0, len); } inStream.close(); return outStream.toByteArray(); }

本方法支持自定义路径:

调用事例:

//urlList 图片的网络地址的集合ArrayList
urlList = new ArrayList
();pictureFileUtil.download(urlList,"c:/demo/..下载的路径");

 亲测好使。。。

转载于:https://www.cnblogs.com/zjiacun/p/7122242.html

你可能感兴趣的文章
Design Pattern --- Strategy
查看>>
mui列表跳转到详情页优化方案
查看>>
一些简单有用的方法合集
查看>>
Neutron 架构 - 每天5分钟玩转 OpenStack(67)
查看>>
详解JS设计模式
查看>>
CPSR寄存器
查看>>
Java基础50题test7—处理字符串
查看>>
保险行业电话外呼型呼叫中心方案
查看>>
自建型呼叫中心
查看>>
input file 文件上传,js控制上传文件的大小和格式
查看>>
Day 6 函数与模块
查看>>
WebApi请求原理
查看>>
[Node.js] node-persist: localStorage on the server
查看>>
jquery.event 研究学习之bind篇
查看>>
LOJ #108. 多项式乘法
查看>>
libusb开发指南
查看>>
SAS基础 -- 逻辑库不存在问题解决
查看>>
Servlet监听器统计在线人数
查看>>
第2章 数字之魅——寻找发帖“水王”
查看>>
eclipse jsp html 格式化 format
查看>>