知道文件名、文件网址,得到zip的输入流(死锁解决)

2 篇文章 0 订阅

import java.io.IOException;
import java.io.InputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.net.URL;
import java.util.Iterator;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import net.sf.json.JSONObject;

public class File2ZipUtil {

/**
 * 将多个文件压缩为zip文件,文件返回输入流
 * @param qualifications 多个(文件名+网址)
 * @param modelId 最终文件存储名
 * @return 返回文件输入流
 * @throws IOException 
 * @throws Exception
 */
@SuppressWarnings("resource")
public static PipedInputStream file2zip(JSONObject qualifications) throws IOException  {

	// 输出流转输入,
	PipedInputStream is = new PipedInputStream();
	// 生成的zip文件
	ZipOutputStream out = new ZipOutputStream(new PipedOutputStream(is));
	
	// 注意:对于管道需要用线程处理,否则会造成死锁
	new Thread(new Runnable() {
		private Log log = LogFactory.getLog(this.getClass());
		public void run() {
			try {
				byte[] buffer = new byte[1024];
				// 网络请求所需变量
				InputStream reader = null;
				URL url = null;
				Iterator<?> it = qualifications.keys();
				while (it.hasNext()) {
					// 获得key和value
					String key = (String)it.next();
					String path = qualifications.getString(key);
					url = new URL(path);
					out.putNextEntry(new ZipEntry(key + path.substring(path.lastIndexOf("."))));
					// 根据Url打开地址,以utf-8编码的形式返回输入流
					reader = url.openStream();
					int len;
					// 读入需要下载的文件的内容,打包到zip文件
					while ((len = reader.read(buffer)) > 0) {
						out.write(buffer, 0, len);
					}
				}
				reader.close();
			} catch (Exception e) {
				log.error("文件读取失败",e);
			}finally {
				try {
					out.closeEntry();
					out.close();
				}catch (Exception e) {
					log.error("文件读取失败",e);
				}
			}
		}
	}).start();
	// 返回最终压缩文件的地址
	return is;
}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值