Java 将文件打包为zip压缩包下载
1、添加依赖
1 2 3 4 5 | <dependency> <groupId>org.apache.ant</groupId> <artifactId>ant</artifactId> <version> 1.10 . 5 </version> </dependency> |
2、编写工具类
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 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 | package com.crtw.util; import org.apache.tools.zip.ZipEntry; import org.apache.tools.zip.ZipOutputStream; import java.io.*; /** * 生成压缩文件 (zip,rar 格式) */ public class CompressUtil { /** * @param sourcePath 要压缩的文件路径 * @param suffix 生成的格式后最(zip、rar) */ public static void generateFile(String sourcePath, String suffix) throws Exception { File file = new File(sourcePath); // 压缩文件的路径不存在 if (!file.exists()) { throw new Exception( "路径 " + sourcePath + " 不存在文件,无法进行压缩..." ); } // 用于存放压缩文件的文件夹 String generateFile = file.getParent() + File.separator + "CompressFile" ; File compress = new File(generateFile); // 如果文件夹不存在,进行创建 if ( !compress.exists() ){ compress.mkdirs(); } // 目的压缩文件 String generateFileName = compress.getAbsolutePath() + File.separator + "AAA" + file.getName() + "." + suffix; // 输入流 表示从一个源读取数据 // 输出流 表示向一个目标写入数据 // 输出流 FileOutputStream outputStream = new FileOutputStream(generateFileName); // 压缩输出流 ZipOutputStream zipOutputStream = new ZipOutputStream( new BufferedOutputStream(outputStream)); generateFile(zipOutputStream,file, "" ); System.out.println( "源文件位置:" + file.getAbsolutePath() + ",目的压缩文件生成位置:" + generateFileName); // 关闭 输出流 zipOutputStream.close(); } /** * @param out 输出流 * @param file 目标文件 * @param dir 文件夹 * @throws Exception */ private static void generateFile(ZipOutputStream out, File file, String dir) throws Exception { // 当前的是文件夹,则进行一步处理 if (file.isDirectory()) { //得到文件列表信息 File[] files = file.listFiles(); //将文件夹添加到下一级打包目录 out.putNextEntry( new ZipEntry(dir + "/" )); dir = dir.length() == 0 ? "" : dir + "/" ; //循环将文件夹中的文件打包 for ( int i = 0 ; i < files.length; i++) { generateFile(out, files[i], dir + files[i].getName()); } } else { // 当前是文件 // 输入流 FileInputStream inputStream = new FileInputStream(file); // 标记要打包的条目 out.putNextEntry( new ZipEntry(dir)); // 进行写操作 int len = 0 ; byte [] bytes = new byte [ 1024 ]; while ((len = inputStream.read(bytes)) > 0 ) { out.write(bytes, 0 , len); } // 关闭输入流 inputStream.close(); } } /** * 递归压缩文件 * @param output ZipOutputStream 对象流 * @param file 压缩的目标文件流 * @param childPath 条目目录 */ private static void zip(ZipOutputStream output,File file,String childPath){ FileInputStream input = null ; try { // 文件为目录 if (file.isDirectory()) { // 得到当前目录里面的文件列表 File list[] = file.listFiles(); childPath = childPath + (childPath.length() == 0 ? "" : "/" ) + file.getName(); // 循环递归压缩每个文件 for (File f : list) { zip(output, f, childPath); } } else { // 压缩文件 childPath = (childPath.length() == 0 ? "" : childPath + "/" ) + file.getName(); output.putNextEntry( new ZipEntry(childPath)); input = new FileInputStream(file); int readLen = 0 ; byte [] buffer = new byte [ 1024 * 8 ]; while ((readLen = input.read(buffer, 0 , 1024 * 8 )) != - 1 ) { output.write(buffer, 0 , readLen); } } } catch (Exception ex) { ex.printStackTrace(); } finally { // 关闭流 if (input != null ) { try { input.close(); } catch (IOException ex) { ex.printStackTrace(); } } } } /** * 压缩文件(文件夹) * @param path 目标文件流 * @param format zip 格式 | rar 格式 * @throws Exception */ public static String zipFile(File path,String format) throws Exception { String generatePath = "" ; if ( path.isDirectory() ){ generatePath = path.getParent().endsWith( "/" ) == false ? path.getParent() + File.separator + path.getName() + "." + format: path.getParent() + path.getName() + "." + format; } else { generatePath = path.getParent().endsWith( "/" ) == false ? path.getParent() + File.separator : path.getParent(); generatePath += path.getName().substring( 0 ,path.getName().lastIndexOf( "." )) + "." + format; } // 输出流 FileOutputStream outputStream = new FileOutputStream( generatePath ); // 压缩输出流 ZipOutputStream out = new ZipOutputStream( new BufferedOutputStream(outputStream)); zip(out, path, "" ); out.flush(); out.close(); return generatePath; } //测试 public static void main(String[] args) { String path = "F:\\Develop\\项目\\crawler" ; String format = "zip" ; try { System.out.println(zipFile( new File(path),format)); } catch (Exception e) { e.printStackTrace(); System.out.println(e.getMessage()); } } } |
3、响应为下载
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | //压缩 String zipFile = CompressUtil.zipFile( new File(rootPath), "zip" ); response.setContentType( "APPLICATION/OCTET-STREAM" ); response.setHeader( "Content-Disposition" , "attachment; filename=company.zip" ); try { //ZipOutputStream out = new ZipOutputStream(response.getOutputStream()); OutputStream out = response.getOutputStream(); File ftp = ResourceUtils.getFile(zipFile); InputStream in = new FileInputStream(ftp); // 循环取出流中的数据 byte [] b = new byte [ 100 ]; int len; while ((len = in.read(b)) !=- 1 ) { out.write(b, 0 , len); } in.close(); out.close(); } catch (Exception e) { e.printStackTrace(); } |
标签:
Java
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通