创建一个公共类ZipUtil,代码如下
/** * 生成压缩包 * * @param pathList * @param fisList * @param zos * @throws IOException */ public static void download(List<String> pathList, List<FileInputStream> fisList, ZipOutputStream zos) throws IOException { for (int i = 0; i < pathList.size(); i++) { String path = pathList.get(i); FileInputStream fis = fisList.get(i); ZipEntry entry = new ZipEntry(path); zos.putNextEntry(entry); byte[] buf = new byte[1024]; int len; while ((len = fis.read(buf)) > 0) { zos.write(buf, 0, len); } zos.closeEntry(); fis.close(); } zos.flush(); zos.close(); }
/** * 压缩包内部的情况 * * @return */ public static List<String> getPathList() { List<String> list = new ArrayList<>(); //下面这些是在压缩包中的路径(第一册、测试、下级测试 都是在压缩包中才生成的) list.add("第一册/测试/1.txt"); list.add("第一册/测试/2.txt"); list.add("第2册/3.txt"); list.add("第3册/测试/下级测试/4.txt"); return list; } /** * 对应的文件数据(在D:\data下建了4个文件用来测试) * * @return * @throws FileNotFoundException */ public static List<FileInputStream> getFisList() throws FileNotFoundException { List<FileInputStream> list = new ArrayList<>(); list.add(new FileInputStream("D:\\data\\1.txt")); list.add(new FileInputStream("D:\\data\\2.txt")); list.add(new FileInputStream("D:\\data\\3.txt")); list.add(new FileInputStream("D:\\data\\4.txt")); return list; } /** * 获取ZipOutputStream * * @return * @throws FileNotFoundException */ public static ZipOutputStream getZos() throws FileNotFoundException { // 实际项目中换成从HttpServletResponse中获取OutputStream // OutputStream os = response.getOutputStream(); OutputStream os = new FileOutputStream("D:\\1.zip"); ZipOutputStream zos = new ZipOutputStream(os); return zos; }
/** * 打包压缩下载文件 */ @RequestMapping(value = "/downloadFile/1", method = RequestMethod.GET) public void downLoadZipFile(HttpServletResponse response) throws IOException{ String zipName = "myfile.zip"; response.setContentType("APPLICATION/OCTET-STREAM"); response.setHeader("Content-Disposition","attachment; filename="+zipName); ZipOutputStream out = new ZipOutputStream(response.getOutputStream()); try { ZipUtils.download(ZipUtils.getPathList(),ZipUtils. getFisList(), out); response.flushBuffer(); } catch (Exception e) { e.printStackTrace(); }finally{ out.close(); } }