java读流方式,下载网络上的图片
本工具类支持url的list集合,具体实现如下所示:
public static void download(ArrayList<String> 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<String> urlList = new ArrayList<String>(); pictureFileUtil.download(urlList,"c:/demo/..下载的路径");
亲测好使。。。
版权声明:本文为zjiacun原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。