Java 下载压缩zip

Java压缩zip

 /**
     * 下载压缩包
     *
     * @param instId   实例id
     * @param response 响应
     * @author 梁伟浩
     * @date 2023-08-21
     */
    @GetMapping("/downloadZip")
    @ApiOperation(value = "下载压缩包")
    @ApiImplicitParam(name = "instId", value = "实例id", required = true, paramType = "query", dataTypeClass = String.class)
    public void downloadZip(@RequestParam("instId") String instId, HttpServletResponse response) {
        Asserts.isEmpty(instId, "实例id[instId]不能为空");
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            businessContentService.zipAttachTree(instId,response);
            outputStream.flush();
        } catch (Exception e) {
            response.setStatus(SC_BAD_REQUEST);
            try {
                if (outputStream != null) {
                    response.setCharacterEncoding("utf-8");
                    response.setHeader("Content-Type", "application/json;charset=utf-8");
                    outputStream.write(JSON.toJSONString(R.fail(e.getMessage())).getBytes());
                }
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
    }
 @Override
    public void zipAttachTree(String instId, HttpServletResponse response) {
        InstBusinessInfo instBusinessInfo = instBusinessInfoMapper.selectById(instId);
        String instTitle = instBusinessInfo.getInstTitle();
        if (instBusinessInfo == null) {
            throw new BusinessException(instId);
        }

        //获取附件树目录
        BusinessContentRequest instanceContentRequest = new BusinessContentRequest();
        BusinessContentResponse contentResponse = null;
        instanceContentRequest.setInstId(instId);
        instanceContentRequest.setGroupEnum(BusinessContentGroupEnum.DIR_TREE);
        try {
            contentResponse = this.getBusinessContent(instanceContentRequest);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<BusinessContentVO> contentVOList = contentResponse.getContentVOList();
        File directory = new File("./" + instTitle);
        directory.mkdir();
        //递归创建文件夹并把文件流放进对应文件夹
        this.getFileName(contentVOList, new StringBuilder(), instTitle);

        File file = new File("./" + instTitle);

        File zipFile = null;
        List<File> souceFileList = new ArrayList();
        try {
            souceFileList.add(file);
            zipFile = new File(instTitle + ".zip");
            ZipUtil.toZip(zipFile.getName(), souceFileList);
            BufferedInputStream fis = new BufferedInputStream(new FileInputStream(zipFile));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(zipFile.getName(), "UTF-8"));
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //删除本地生成的文件夹与zip压缩包
            if (file!=null && file.exists()){
                FileUtil.del(file);
            }
            if (zipFile != null && zipFile.exists()) {
                zipFile.delete();
            }
        }
    }



    //递归生成文件夹并把流写到对应文件夹
    public void getFileName(List<BusinessContentVO> contentVOList, StringBuilder sb, String instTitle) {
        List<StringBuilder> fileNames = new ArrayList<>();
        for (BusinessContentVO contentVO : contentVOList) {
            OutputStream outputStream = null;
            StringBuilder newSb = new StringBuilder(sb); // 创建新的 StringBuilder 对象
            if (Func.isEmpty(contentVO.getDataId())) {
                File directory = new File("./" + instTitle + "/" + contentVO.getNodeName());
                directory.mkdir();
                newSb.append(contentVO.getNodeName() + "/");
            } else {
                String dataId = contentVO.getDataId();
                InstFileInfo instFileInfo = instFileInfoMapper.selectById(dataId);
                InputStream inputStream = minioTemplate.getObject(instFileInfo.getFilePath());
                String fileName = "./" + instTitle + "/" + sb + "/" + contentVO.getNodeName() + "";
                File outputFile = new File(fileName);
                try {
                    //把文件夹创建成输出文件
                    outputStream = new FileOutputStream(outputFile);
                    byte[] buffer = new byte[1024];
                    int length;
                    //把文件写到对应的文件夹中
                    while ((length = inputStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, length);
                    }
                    inputStream.close();
                    outputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            List<BusinessContentVO> childrenList = contentVO.getChildren();
            if (childrenList != null) {
                getFileName(childrenList, newSb, instTitle); // 递归调用时使用新的 StringBuilder 对象
            }
        }
    }

将流写到文件中

 MultipartFile file
 InputStream is = file.getInputStream();
 ZipInputStream zipInputStream = new ZipInputStream(is, Charset.forName("UTF-8"));
  File jsonFile = new File("./pre/" + zipEntryNameStr);
  this.writeFile(jsonFile.getAbsolutePath(), zipInputStream);

    /**
     * @描述 将流写到文件中
     * @作者 吕嘉伟
     * @日期 2023/3/30 17:49
     */
    public void writeFile(String filePath, ZipInputStream zipInputStream) {
        try (OutputStream outputStream = new FileOutputStream(filePath)) {
            byte[] bytes = new byte[4096];
            int len;
            while ((len = zipInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
            }
        } catch (IOException ex) {
            System.out.println("解压文件时,写出到文件出错");
        }
    }

你可能感兴趣的:(java,python,windows)