转自:https://blog.csdn.net/lvoelife/article/details/108620182
/** * 压缩文件 * @param fileIds 文件id:根据id可获取文件 * @param packageName 下载压缩文件包名 * @param response */ public void downLoadZipFile(List<Long> fileIds,String packageName,HttpServletResponse response){ OutputStream out = null; ZipOutputStream zos = null; BufferedInputStream bis = null; try { if (CollectionUtil.isNotEmpty(fileIds)){ out = response.getOutputStream(); //创建压缩文件需要的空的zip包 String zipName = packageName + System.currentTimeMillis() + ".zip"; String zipFilePath = temPath + File.separator + zipName; //压缩文件 File zip = new File(zipFilePath); if (!zip.exists()) { zip.createNewFile(); } //创建zip文件输出流 zos = new ZipOutputStream(new FileOutputStream(zip)); zipFile(fileIds, zos); response.setContentType("text/html; charset=UTF-8"); //设置编码字符 response.setContentType("application/octet-stream"); //设置内容类型为下载类型 response.setHeader("Content-disposition", "attachment;filename=" + zipName);//设置下载的文件名称 //将打包后的文件写到客户端,输出的方法同上,使用缓冲流输出 bis = new BufferedInputStream(new FileInputStream(zipFilePath)); byte[] buff = new byte[bis.available()]; bis.read(buff); out.flush();//释放缓存 out.write(buff);//输出数据文件 } } catch (IOException e) { e.printStackTrace(); log.error("-------------文件下载失败----------------"); } catch (Exception e) { e.printStackTrace(); } finally { doClose(bis, out, zos); } } private void doClose(InputStream inputStream, OutputStream... outputStreams) { try { if (inputStream != null) { inputStream.close(); } if (outputStreams != null && outputStreams.length > 0) { for (OutputStream outputStream : outputStreams) { outputStream.close(); } } } catch (IOException e) { e.printStackTrace(); } } private void zipFile(List<Long> FileIds, ZipOutputStream zos) throws Exception { for (Long fileId : FileIds) { FileBox fileBox = getFileById(fileId); File inputFile = fileBox.getFile(); //创建输入流读取文件 BufferedInputStream bi = new BufferedInputStream(new FileInputStream(inputFile)); //将文件写入zip内,即将文件进行打包 zos.putNextEntry(new ZipEntry(inputFile.getName())); //写入文件的方法,同上 int size = 0; byte[] buffer = new byte[1024]; //设置读取数据缓存大小 while ((size = bi.read(buffer)) > 0) { zos.write(buffer, 0, size); } //关闭输入输出流 zos.closeEntry(); bi.close(); } zos.close(); }
标签:ZipOutputStream,OutputStream,java,zip,bis,zos,new,response,out From: https://www.cnblogs.com/person008/p/16742351.html