Java多文件生成压缩包

1. 生成压缩包需要引入ZipOutputStream类

//获取目标文件输入流
InputStream is = Files.newInputStream("目标文件路径");

//构建生成压缩文件的格式
zipOutputStream.putNextEntry(new ZipEntry("生成压缩包内的路径"));

//将输入流写入压缩包
int readLen;
byte[] buffer = new byte[1024];
while ((readLen = is.read(buffer)) != -1) {
   zipOutputStream.write(buffer, 0, readLen);
}

2. 最近项目中写的DEMO代码

  1. 记录需要压缩的文件名和文件输入流
    public Map record(String path, String preDir) throws IOException {

        Map fileMap = new HashMap<>();

        Files.walkFileTree(Paths.get(path), new SimpleFileVisitor() {
            //同名文件加前缀
            private int count = 2;

            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                  //文件为空则存null值区分
                  if (Files.list(dir).count() == 0) {
                    fileMap.put(null, null);
                }
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                InputStream is = Files.newInputStream(file);
                if (fileMap.containsKey(preDir + File.separator + file.getFileName().toString())) {
                    StringBuffer sb = new StringBuffer(preDir + File.separator + count + "_");
                    sb.append(file.getFileName().toString());
                    fileMap.put(sb.toString(), is);
                    count++;
                } else {
                    StringBuffer sb2 = new StringBuffer(preDir + File.separator);
                    sb2.append(file.getFileName().toString());
                    fileMap.put(sb2.toString(), is);
                }
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                logger.error("文件:{},访问失败:{}", file.getFileName().toString(), exc.getMessage(), exc);
                return FileVisitResult.CONTINUE;
            }
        });
        return fileMap;
    }
  1. 整合SpringMVC把文件响应给页面
    
    @RequestMapping("/downzip")
    public void getFile(HttpServletResponse response) {

        response.setContentType("application/octet-stream");
        try {
            response.setHeader("Content-disposition", "attachment;filename="
                    + new String("预约ID.zip".getBytes("UTF-8"), "ISO8859-1")
            );
        } catch (UnsupportedEncodingException e) {
            logger.error("响应头出错:{}", e.getMessage(), e);
        }
        response.setHeader("Accept-Ranges", "bytes");
        Map videoMap = new HashMap<>();
        Map videopicMap = new HashMap<>();
        Map videoAttchMap = new HashMap<>();
        try {
            //视频文件
            videoMap = record("E:\\video\\999\\", "video");
            //图片文件
            videopicMap = record("E:\\videopic\\999", "videopic");
            //附件文件
            videoAttchMap = record("E:\\videoAttch\\999", "videoAttch");
        }catch (IOException e){

        }
        List> mapList = new ArrayList<>(3);
        mapList.add(videoMap);
        mapList.add(videopicMap);
        mapList.add(videoAttchMap);
        zipMultipleFiles2(response, mapList);

    }
  1. 遍历记录好的文件输入流集合
    /**
     * 将存储的流添加压缩包并响应给调用者
     * @param response 
     * @param mapList
     */
    public void zipMultipleFiles(HttpServletResponse response, List> mapList) {

        try (ZipOutputStream zipOutputStream = new ZipOutputStream(response.getOutputStream())) {
            // 遍历每一个文件,进行压缩
            for (Map map : mapList) {
                Iterator> it = map.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry entry = it.next();
                    String path = entry.getKey();
                    InputStream is = entry.getValue();
                    if (Objects.equals(path, null) || Objects.equals(is, null)) {
                        continue;
                    }
                    zipOutputStream.putNextEntry(new ZipEntry(path));
                    int readLen;
                    byte[] buffer = new byte[1024];
                    while ((readLen = is.read(buffer)) != -1) {
                        zipOutputStream.write(buffer, 0, readLen);
                    }
                    entry.getValue().close();
                    zipOutputStream.closeEntry();
                }
            }
        } catch (IOException e) {        
            logger.error("出现错误:{}", e.getMessage(), e);
        }
    }
  1. 压缩包效果


    压缩包效果图

你可能感兴趣的:(Java多文件生成压缩包)