zoukankan      html  css  js  c++  java
  • 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/..下载的路径");
    

     亲测好使。。。

  • 相关阅读:
    delphi7下调用微软的Web Services的心得
    Asp.net组件设计浅论
    STC系统烧写及STC12C5A60S2最小系统
    ENET 1.3.3 VC2005 下使用
    ENet library compilation record
    51定时器
    可靠的UDP编程(ENET库)
    ASP.NET MVC3布局页与分布页调用方式概述
    排除JQuery通过HttpGet调用WebService返回Json时“parserror”错误
    AJAX数据源协调处理思路
  • 原文地址:https://www.cnblogs.com/zjiacun/p/7122242.html
Copyright © 2011-2022 走看看