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/..下载的路径");
    

     亲测好使。。。

  • 相关阅读:
    css+ul+li方式 横向再纵向排列
    b表中有的塞给a表
    .net remoting的两种实现方式 cow
    Prism之Module cow
    2012项目总结 cow
    WCF学习笔记 cow
    也谈委托,事件和回调 cow
    理清apply(),call()的区别和关系 cow
    CLR via C#学习之线程栈,托管堆,值类型和引用类型 cow
    细说系列笔记 cow
  • 原文地址:https://www.cnblogs.com/zjiacun/p/7122242.html
Copyright © 2011-2022 走看看