Java: 生成多级ZIP压缩文件

java标志
image-3245

代码如下(maven项目,依赖Spring Boot,Spring Web等):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
 // log: 使用Lombok的@Slf4j.

  /**
  *
  * 获取zip文件
  *
  */

  @GetMapping("/get-zip")
  public void getZip(
      HttpServletResponse response) {
    String fileName = "xxx_file";
    byte[] data = genData();
    try {
      genZip(response, data, fileName);
    } catch (IOException e) {
      log.error(
          "发生异常,异常信息: {}",
          e.getMessage());
      e.printStackTrace();
    }
  }

 /**
  * 生成数据.
  *
  */

  public byte[] genData() throws IOException {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    ZipOutputStream zipOut = new ZipOutputStream(outputStream);
    try{
          // 给压缩文件中添加多个文件,可以设置文件名.
          Collections.emptyList().forEach(
            item -> {
              Random random=new Random();
              int id=random.nextInt();
              String fileName =
                  item + "_" + id + ".json";
              try {
                // 设置文件名
                zipOut.putNextEntry(new ZipEntry(fileName));
                // 添加文件内容
                zipOut.write(fileName.getBytes(StandardCharsets.UTF_8));
              } catch (IOException e) {
                log.error(
                    "获取数据失败,失败原因: {}",
                    e.getMessage());
                e.printStackTrace();
              }
          });
    } finally {
      try {
        zipOut.closeEntry();
        zipOut.close();
        outputStream.close();
      } catch (IOException e) {
        log.error(
            "关闭数据压缩失败,失败原因: {}",
            e.getMessage());
        e.printStackTrace();
      }
    }

    return outputStream.toByteArray();
  }



  /**
   * 压缩文件输出.
   *
   * @param response 响应
   * @param data 数据
   * @param fileName 文件名
   * @throws IOException IO异常
   */

  private void outZip(HttpServletResponse response, byte[] data, String fileName)
      throws IOException {
    response.reset();
    response.addHeader("Access-Control-Allow-Origin", "*");
    response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
    response.setHeader("Content-Disposition", "attachment; filename="" + fileName + ".zip"");
    response.addHeader("Content-Length", "" + data.length);
    response.setContentType("application/octet-stream; charset=UTF-8");
    org.apache.commons.io.IOUtils.write(data, response.getOutputStream());
  }

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

*

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据