把文件压缩成zip包并设置密码
引入依赖
1 2 3 4 5 6 | <!-- zip --> <dependency> <groupId>net.lingala.zip4j</groupId> <artifactId>zip4j</artifactId> <version> 1.3 . 2 </version> </dependency> |
代码
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 | 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; } } |
分类:
给excel设置密码
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通