首页 > 解决方案 > 在 Java 中创建受密码保护的 zip 文件,而不在磁盘上创建它

问题描述

我需要一个创建 zip 文件。它应该受密码保护。我正在使用 lingala jar。这是我的下面。有没有办法做到这一点?我什至尝试了 zipoutstream,找不到添加密码的方法。

@Component
public class FileZipUtils {

    @Value("${candela.email.zip.folder}")
    private String zipBaseDir;

    @Value("${candela.email.zip.encryptionmethod:AES}")
    private String encryptionMethod;

    @Value("${candela.email.zip.encryptionstrength:KEY_STRENGTH_128}")
    private String encryptionStrength;

    private ZipParameters zipParameters;

    @PostConstruct
    private void initializeZipProperties() {
        zipParameters = new ZipParameters();
        zipParameters.setEncryptFiles(true);
        zipParameters.setEncryptionMethod(EncryptionMethod.AES);
        zipParameters.setAesKeyStrength(AesKeyStrength.KEY_STRENGTH_128);
    }

    /*
     * Creates a zipfile in the zipBaseDir location
     */
    public ZipFile createZipFile(String zipFileName,char[] password) {
        return new ZipFile(zipBaseDir + "/" + zipFileName,password);
    }

    /**
     * Adds attachment to Zip file
     */
    public void addAttachementToZip(ZipFile zipFile, ByteArrayResource fileContentInBytes, String fileName)
            throws IOException {
        zipParameters.setFileNameInZip(fileName);
        zipFile.addStream(fileContentInBytes.getInputStream(), zipParameters);
    }

}

标签: javazip

解决方案


zip4jzip 文件库的最佳解决方案。(Github 链接

特征:

  • 从 Zip 文件中创建、添加、提取、更新、删除文件
  • 支持流(ZipInputStream 和 ZipOutputStream)
  • 读/写受密码保护的 Zip 文件和流
  • 支持 AES 和 Zip-Standard 加密方法
  • 支持 Zip64 格式
  • 存储(无压缩)和 Deflate 压缩方法
  • 从拆分 Zip 文件中创建或提取文件(例如:z01、z02、...zip)
  • 支持 zip 中的 Unicode 文件名和注释
  • 进度监视器 - 用于集成到应用程序和面向用户的应用程序中

推荐阅读