生活随笔
收集整理的這篇文章主要介紹了
java实现多文件批量下载总结
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在工作上回遇到很多需要進行文件批量下載的需求,將多個文件合并成一個zip壓縮包進行下載
之前也是參考了其他大佬的博客才有個人使用的總結 在此表示感謝
直接上代碼
public void downForZip(HttpServletRequest req
, HttpServletResponse response
,List<FileInfo> fileInfoList
) {File zipFile
= null;FileInputStream fis
= null;BufferedInputStream buff
= null;try {zipFile
= File.createTempFile("test", ".zip");FileOutputStream fot
= new FileOutputStream(zipFile
);CheckedOutputStream cos
= new CheckedOutputStream(fot
, new Adler32());ZipOutputStream zos
= new ZipOutputStream(cos
);for (FileInfo file
: fileInfoList
) {InputStream inputStream
= fileService
.getFileInpuStream(file
.getId(), file
.getKey());if (null == inputStream
) {break;}zos
.putNextEntry(new ZipEntry(file
.getFileName()));int bytesRead
= 0;while ((bytesRead
= inputStream
.read()) != -1) {zos
.write(bytesRead
);}inputStream
.close();zos
.closeEntry();}zos
.close();ServletOutputStream os
= response
.getOutputStream();response
.setCharacterEncoding("GB2312");response
.setContentType(req
.getSession().getServletContext().getMimeType(file
.getFileName()));response
.setHeader("content-disposition", "attachment;fileName=" + URLEncoder.encode("批量下載.zip", "UTF-8"));fis
= new FileInputStream(zipFile
);buff
= new BufferedInputStream(fis
);FileCopyUtils.copy(buff
, os
);} catch (Exception e1
) {throw new BusinessException("批量下載失敗");} finally {try {if (null != fis
) {fis
.close();}if (null != buff
) {buff
.close();}} catch (IOException e
) {log
.error( "流關閉異常");}if (null != zipFile
) {zipFile
.delete();}}}
總結
以上是生活随笔為你收集整理的java实现多文件批量下载总结的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。