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;
}
}
Java从网络资源URL中获取IO流打包压缩成zip文件并下载
最新推荐文章于 2023-08-02 22:41:26 发布