Java根据Url下载图片

原文地址:https://blog.csdn.net/ro_wsy/article/details/24673333
https://www.cnblogs.com/xiayuscc/p/5555498.html

package com.qjzh.zhwg.modules.cmd.util;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import com.qjzh.zhwg.exception.BusinessException;

public class DownloadPicture {

	public static void main(String[] args) {
		DownloadPicture downloadPicture = new DownloadPicture();
		ArrayList<String> urlList = new ArrayList<>();
		urlList.add("http://192.168.49.10:9999/file-download?fileId=4028b18a6956cb3f01696bf079e90040&moder=2");
		downloadPicture.downloadPicture(urlList);
	}

	/**
	 * 传入要下载的图片的url列表,将url所对应的图片下载到本地
	 * 
	 * @param urlList
	 * @throws BusinessException
	 */
	public static void downloadPicture(Object urlString, String imagePath, String name) throws BusinessException {

		File file = new File(imagePath);
		if (!file.exists()) {
			file.mkdirs();
		}

		if (urlString == null) {
			throw new BusinessException("下载图片地址为空");
		}
		URL url = null;
		try {
			url = new URL(urlString.toString());

			DataInputStream dataInputStream = new DataInputStream(url.openStream());
			FileOutputStream fileOutputStream = new FileOutputStream(new File(imagePath + File.separator + name));

			byte[] buffer = new byte[1024];
			int length;

			while ((length = dataInputStream.read(buffer)) > 0) {
				fileOutputStream.write(buffer, 0, length);
			}

			dataInputStream.close();
			fileOutputStream.close();
		} catch (MalformedURLException e) {
			e.printStackTrace();
			throw new BusinessException("下载、保存图片失败" + urlString);
		} catch (IOException e) {
			e.printStackTrace();
			throw new BusinessException("保存图片失败" + urlString);
		}
	}

	/**
	 * 传入要下载的图片的url列表,将url所对应的图片下载到本地
	 * 
	 * @param urlList
	 */
	private void downloadPicture(ArrayList<String> urlList) {
		URL url = null;
		int imageNumber = 100;

		for (String urlString : urlList) {
			try {
				url = new URL(urlString);
				DataInputStream dataInputStream = new DataInputStream(url.openStream());
				String imageName = "D:\\capture\\program\\" + imageNumber + ".jpg";
				FileOutputStream fileOutputStream = new FileOutputStream(new File(imageName));

				byte[] buffer = new byte[1024];
				int length;

				while ((length = dataInputStream.read(buffer)) > 0) {
					fileOutputStream.write(buffer, 0, length);
				}

				dataInputStream.close();
				fileOutputStream.close();
				imageNumber++;
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值