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

     亲测好使。。。

  • 相关阅读:
    初试ASP.NET Web API/MVC API(附Demo)
    IP网络,光网络以及轨道交通的快速卸载随想
    解决Cocos2d-x3.0、3.1 &quot;_opendir$INODE64&quot;symbol(s) not found错误
    C strlen vs sizeof
    xUtils工具实现下载功能
    使用 PHPMailer 发送邮件
    自己定义TextView 调用ttf格式字体
    POJ
    C#实现麦克风採集与播放
    用程序来控制一个网页,实现自己主动输入等操作
  • 原文地址:https://www.cnblogs.com/zjiacun/p/7122242.html
Copyright © 2011-2022 走看看