Java根据URL下载图片

本文介绍了一种使用Java实现的图片下载方法,通过URL获取图片并保存至指定路径。该方法利用了java.io包中的InputStream和OutputStream进行数据读写,适用于网络图片资源的批量下载场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

导入的包都是java.io中的 

/**
	 * 下载图片
	 * @param urlString
	 * @param filename 文件路径
	 * @param savePath 保存路径
	 */
	public static Map<String, Object> download(String filename ,String savePath){
		Map<String, Object> res = new HashMap<String, Object>();
		String code = Constants.SUCCESS;
		String msg = "下载成功:图片存放在:C://";
		// 构造URL
		InputStream is = null;
		OutputStream os = null;
		try {
			java.net.URL url = new java.net.URL(filename );
			 // 打开连接
		    URLConnection con = url.openConnection();
		    // 输入流
		    is = con.getInputStream();
		    // 1K的数据缓冲
		    byte[] bs = new byte[1024];
		    // 读取到的数据长度
		    int len;
		    // 输出的文件流
		    os = new FileOutputStream(savePath);
		    // 开始读取
		    while ((len = is.read(bs)) != -1) {
		      os.write(bs, 0, len);
		    }
		} catch (Exception e) {
			e.printStackTrace();
			code = "999";
			msg = "下载失败";
		} finally {
		    try {
		    	// 完毕,关闭所有链接
		    	if (null != is && null != os) {
		    		is.close();
		    		os.close();
		    	}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	    
	    res.put("code", code);
	    res.put("msg", msg);
	    return res;
	}
	

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值