<dependency> <groupId>net.lingala.zip4j</groupId> <artifactId>zip4j</artifactId> <version>2.6.4</version> </dependency>
public static void zip(File currentDir, String toFilePath, String password) throws Exception { // 生成的壓縮文件 ZipFile zipFile = new ZipFile(toPath); ZipParameters parameters = new ZipParameters(); // 壓縮方式 parameters.setCompressionMethod(CompressionMethod.DEFLATE); // 壓縮級別 parameters.setCompressionLevel(CompressionLevel.NORMAL); // 是否設置加密文件 parameters.setEncryptFiles(true); // 設置加密算法 parameters.setEncryptionMethod(EncryptionMethod.AES); // 設置AES加密密鑰的密鑰強度 parameters.setAesKeyStrength(AesKeyStrength.KEY_STRENGTH_256); // 設置密碼 if(!Strings.isNullOrEmpty(password)) { zipFile.setPassword(password.toCharArray()); } // 要打包的文件夾 File[] fs = currentDir.listFiles(); // 遍歷test文件夾下所有的文件、文件夾 for (File f : fList) { if (f.isDirectory()) { zipFile.addFolder(f, parameters); } else { zipFile.addFile(f, parameters); } } }
public static void unzip(String zipFilePath, String toPath, String password) throws Exception { // 生成的壓縮文件 ZipFile zipFile = new ZipFile(zipFilePath); // 設置密碼 if(!Strings.isNullOrEmpty(password)) { zipFile.setPassword(password.toCharArray()); } // 解壓縮所有文件以及文件夾 zipFile.extractAll(toPath); }