java 生成帶資料夾的壓縮包zip
阿新 • • 發佈:2021-01-22
問題
某天產品baba,提了一個需求,企業下載檔案壓縮包,需要按類別歸類全部的檔案。壓縮包結構如下圖:
某某企業檔案.zip | ||
資料夾1 | ||
a.jpg | ||
b.jpg | ||
資料夾2 | ||
a.jpg | ||
b.jpg | ||
資料夾3 | ||
a.jpg |
解決辦法
找了網上很多方法,基本都是壓縮包裡面直接放檔案的。
經過自己多次跳坑終於找到可行辦法,
關鍵就是方法的路徑寫法,如下:
(zos.putNextEntry(new ZipEntry("資料夾"+i + File.separator + sourceFile.getName()));)。
資料夾名稱+ 分隔符 +檔名
程式碼如下:
package com.example.demo; import java.io.*; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; /** * @Description: 帶資料夾的壓縮 * @author: luog * @Date: 2021/1/20 * @param: null * @returns: */ public class Common { private static final int BUFFER_SIZE = 2 * 1024; /** * @Description: 生成帶目錄的檔案壓縮包 * @author: luog * @Date: 2021/1/20 * @param: srcDir 原始檔路徑 * @param: outDir 最終檔名 * @param: KeepDirStructure * @returns: void */ public static void createZip(String srcDir, String outDir) throws RuntimeException, Exception { byte[] buf = new byte[BUFFER_SIZE]; try { File sourceFile = new File(srcDir); ZipOutputStream zos = null; OutputStream out = new FileOutputStream(new File(outDir)); //模擬生成是三個資料夾 每個資料夾放一個檔案 for (int i = 0; i < 3; i++) { //web 請求請用response 構建輸出流 // response.setCharacterEncoding("gb2312"); // response.setHeader("Content-Disposition", "attachment; filename=企業檔案.zip"); // zos = new ZipOutputStream(response.getOutputStream()); //本地測試用 用輸出檔案路徑和名稱 構建輸出流 zos = new ZipOutputStream(out); zos.putNextEntry(new ZipEntry("資料夾"+i + File.separator + sourceFile.getName())); int len; FileInputStream in = new FileInputStream(sourceFile); while ((len = in.read(buf)) != -1) { zos.write(buf, 0, len); } zos.closeEntry(); } zos.close(); System.out.println("壓縮完成"); } catch (Exception e) { throw e; } } /** * @Description: 本地測試 * @author: luog * @Date: 2021/1/21 * @param: args * @returns: void */ public static void main(String[] args) throws Exception { //本地檔案路徑 String localDir="D:\\img1\\xx.jpg"; //輸出檔案路徑和名稱 String outDir = "D:\\某某企業全部檔案.zip"; createZip(localDir, outDir); } }
最終效果截圖;
注意:web 請求請用response 構建輸出流
希望能幫到你!!!
點個贊吧!!!