Java从网络资源URL中获取IO流打包压缩成zip文件并下载

1 篇文章 0 订阅
1 篇文章 0 订阅
import org.apache.commons.io.IOUtils;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

/**
	 * 从多资源文件路径获取文件流,打包成Zip压缩包
	 *
	 * @param filePaths 文件路径列表 eg: https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png
	 */
	public static void getZipFile(List<String> filePaths, HttpServletResponse response) {
		String zipFileName = UUID.randomUUID().toString() + ".zip";
		File zipFile = new File(zipFileName);
		try {
			/* 文件输出流 */
			FileOutputStream outputStream = new FileOutputStream(zipFile);
			/* 压缩流 */
			ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
			/* 字符集GBK */
			zipOutputStream.setEncoding("gbk");
			/* 最大流为10MB */
			final int MAX_BYTE = 10 * 1024 * 1024;
			filePaths.forEach(path -> {
				try {
					String fileName = path.substring(path.lastIndexOf("/") + 1);
					InputStream io = BaseUtil.HttpGetInputStream(path);
					if (io == null) return;
					BufferedInputStream bis = new BufferedInputStream(io);
					ZipEntry entry = new ZipEntry(fileName);
					zipOutputStream.putNextEntry(entry);
					byte[] buffer = new byte[MAX_BYTE]; // byte数据接受文件的数据
					int len;
					while ((len = bis.read(buffer)) != -1) {
						zipOutputStream.write(buffer, 0, len);
					}
					/* 关闭当前的zip entry */
					zipOutputStream.closeEntry();

					/* 关闭流 */
					bis.close();
					io.close();

				} catch (Exception e) {
					e.printStackTrace();
				}
			});
			/* 关闭压缩流、文件流 */
			try {
				zipOutputStream.close();
				outputStream.close();
				response.addHeader("content-disposition", "attachment;filename=" + zipFileName);
				FileInputStream fio = new FileInputStream(zipFile);
				IOUtils.copy(fio, response.getOutputStream());
				fio.close();
				zipFile.delete();
			} catch (IOException e) {
				e.printStackTrace();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}

	}


	public static InputStream HttpGetInputStream(String GetUrl) {
		/* 链接 */
		HttpURLConnection connection = null;
		//
		InputStream io = null;
		try {
			connection = (HttpURLConnection) new URL(GetUrl).openConnection();
			connection.setRequestMethod("GET");
			connection.setConnectTimeout(30000);
			connection.setReadTimeout(30000);
			connection.connect();
			int code = connection.getResponseCode();
			if (!(code == 200)) {
				return null;
			}
			io = connection.getInputStream();
			return io;
		} catch (Exception e) {
			e.printStackTrace();
			if (connection != null) {
				connection.disconnect();
			}
			return null;
		}
	}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值