AdvancedZipUtils.java 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package com.kingdee.eas.custom.compensation.utils;
  2. import java.io.*;
  3. import java.util.Map;
  4. import java.util.zip.*;
  5. /**
  6. * @Description TODO
  7. * @Date 2025/9/29 14:37
  8. * @Created by 59279
  9. */
  10. public class AdvancedZipUtils {
  11. /**
  12. * 创建压缩包并设置压缩级别
  13. */
  14. public static void createZipWithCompressionLevel(byte[] fileData, String fileName,
  15. String zipFilePath, int compressionLevel) {
  16. try (FileOutputStream fos = new FileOutputStream(zipFilePath);
  17. ZipOutputStream zos = new ZipOutputStream(fos)) {
  18. // 设置压缩级别 (0-9, 0=不压缩, 9=最大压缩)
  19. zos.setLevel(compressionLevel);
  20. // 设置注释
  21. zos.setComment("Created by Java Zip Utils");
  22. ZipEntry entry = new ZipEntry(fileName);
  23. zos.putNextEntry(entry);
  24. zos.write(fileData);
  25. zos.closeEntry();
  26. } catch (IOException e) {
  27. e.printStackTrace();
  28. }
  29. }
  30. /**
  31. * 创建带目录结构的压缩包
  32. */
  33. public static void createZipWithDirectory(byte[] fileData, String filePathInZip,
  34. String zipFilePath) {
  35. try (FileOutputStream fos = new FileOutputStream(zipFilePath);
  36. ZipOutputStream zos = new ZipOutputStream(fos)) {
  37. ZipEntry entry = new ZipEntry(filePathInZip);
  38. zos.putNextEntry(entry);
  39. zos.write(fileData);
  40. zos.closeEntry();
  41. } catch (IOException e) {
  42. e.printStackTrace();
  43. }
  44. }
  45. /**
  46. * 创建多个文件压缩包
  47. */
  48. public static void createZipFromMultipleFiles(Map<String, byte[]> files, String zipFilePath) {
  49. try (FileOutputStream fos = new FileOutputStream(zipFilePath);
  50. ZipOutputStream zos = new ZipOutputStream(fos)) {
  51. for (Map.Entry<String, byte[]> file : files.entrySet()) {
  52. ZipEntry entry = new ZipEntry(file.getKey());
  53. zos.putNextEntry(entry);
  54. zos.write(file.getValue());
  55. zos.closeEntry();
  56. }
  57. } catch (IOException e) {
  58. e.printStackTrace();
  59. }
  60. }
  61. }