引入依赖
<!-- zip --> <dependency> <groupId>net.lingala.zip4j</groupId> <artifactId>zip4j</artifactId> <version>1.3.2</version> </dependency>
代码
package org.example; import java.io.File; import net.lingala.zip4j.core.ZipFile; import net.lingala.zip4j.exception.ZipException; import net.lingala.zip4j.model.ZipParameters; import net.lingala.zip4j.util.Zip4jConstants; public class CustomExport { private static String zipFilePassword = "1234568"; public static void main(String[] args) throws ZipException { String zipPath="C:\\Users\\50649\\Desktop\\test"; String fileName="666.xlsx"; String fold="C:\\Users\\50649\\Desktop\\test\\666.xlsx"; File folderPath = new File(fold); zipFile(zipPath,fileName, folderPath); } /** * @param zipPath * 创建zip文件的 文件路径+zip名称 * @param folderPath * 待压缩文件夹或者待压缩文件 */ private static String zipFile(String zipPath,String fileName, File folderPath) throws ZipException { // 切割.后缀名 不然文件下载后缀名为xlszip 虽然也是zip文件,但会让人感觉很奇怪 // java中的.需要转义 \\. 才是. String []fastFileName = null; if (null != fileName) { fastFileName = fileName.split("\\."); } fileName = fastFileName[0]; ZipFile zipFile = new ZipFile(zipPath+"\\"+fileName+".zip"); ZipParameters parameters = new ZipParameters(); // 设置zip包的一些参数集合 parameters.setEncryptFiles(true); // 是否设置密码(此处设置为:是) parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE); // 压缩方式(默认值) parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL); // 普通级别(参数很多) parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_STANDARD); // 加密级别 parameters.setPassword(zipFilePassword); // 压缩包密码 if (folderPath.isDirectory()) { zipFile.createZipFileFromFolder(folderPath, parameters, false, -1L); } else { zipFile.createZipFile(folderPath, parameters); } return zipFile.getFile().getName(); } /** * 压缩完成后删除excel文件 */ private static boolean deleteFile(String sPath) { boolean flag = false; File file = new File(sPath); // 路径为文件且不为空则进行删除 if (file.isFile() && file.exists()) { file.delete(); flag = true; } return flag; } }
标签:folderPath,zip,String,parameters,压缩成,fileName,包并,zip4j From: https://www.cnblogs.com/xianz666/p/18208919