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;
}
}