java下載打包成zip

隨筆

1、調用

    // 導出歸檔件
    // 若是沒有選中則導出全部,選中則按照選中Laura
    public void plistDownLoad() throws Exception {
        String fileIds = request.getParameter ("fileIds");

        // 此處模擬處理ids,拿到文件下載url
        List<String> paths = new ArrayList<> ( );
        String realPath = request.getSession ( ).getServletContext ( ).getRealPath ("/");// 鎖定工程路徑下(Windows)
        String url = realPath + "upload\\pdf2\\";// 統一文件夾地址
        
        if ( DailyUtil.isStringEmpty (fileIds)){// 不為空的逗號隔開字符串,填充
            String[] split = fileIds.split (",");
            if (DailyUtil.isArray (split)){
                for (String pdfName : split) {
                    String filePath = url + pdfName+ ".pdf";// 組合的最終路徑
                    paths.add (filePath);
                }
            }
        }else {// 不選中則導出所有(遍歷整個 目錄)
            String fNames = DailyFileUtil.folderMethod2 (url);
            String[] split = fNames.split (",");
            if (DailyUtil.isArray (split)){
                for (String pdfName : split) {
                    String filePath = url + pdfName;// 組合的最終路徑
                    paths.add (filePath);
                }
            }
        }
        

        // paths.add ("C:\\Users\\E480\\Desktop\\Study\\casul筆記.txt");
//        paths.add ("C:\\Users\\E480\\Desktop\\Study\\config配置中心筆記.txt");
//        paths.add ("C:\\Users\\E480\\Desktop\\Study\\GateWay.txt");
        if (paths.size ( ) != 0) {
            // 創建臨時路徑,存放壓縮文件
            File dir = new File(url+"\\zip");
            if (!dir.exists()) {// 判斷目錄是否存在     
                dir.mkdir();
            }
            
            String zipFilePath = url+"\\zip\\myzip.zip";

            // 壓縮輸出流,包裝流,將臨時文件輸出流包裝成壓縮流,將所有文件輸出到這里,打成zip包
            ZipOutputStream zipOut = new ZipOutputStream (new FileOutputStream (zipFilePath));
            // 循環調用壓縮文件方法,將一個一個需要下載的文件打入壓縮文件包
            for (String path : paths) {
                // 該方法在下面定義
                DailyFileUtil.fileToZip (path, zipOut);
            }
            // 壓縮完成后,關閉壓縮流
            zipOut.close ( );

            //拼接下載默認名稱并轉為ISO-8859-1格式
            String fileName = new String (("出國出境歸檔壓縮文件.zip").getBytes ( ), "ISO-8859-1");
            response.setHeader ("Content-Disposition", "attchment;filename=" + fileName);

            //該流不可以手動關閉,手動關閉下載會出問題,下載完成后會自動關閉
            ServletOutputStream outputStream = response.getOutputStream ( );
            FileInputStream inputStream = new FileInputStream (zipFilePath);
            // 如果是SpringBoot框架,在這個路徑
            // org.apache.tomcat.util.http.fileupload.IOUtils產品
            // 否則需要自主引入apache的 commons-io依賴
            // copy方法為文件復制,在這里直接實現了下載效果
            IOUtils.copy (inputStream, outputStream);

            // 關閉輸入流
            inputStream.close ( );

            //下載完成之后,刪掉這個zip包
            File fileTempZip = new File (zipFilePath);
            fileTempZip.delete ( );
        }
    }

工具方法

package com.jh.jcs.attence.calendar.util;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletOutputStream;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/*
 * @Description:    操作文件的工具集
 * @Author:         Jk_kang
 * @CreateDate:     2021/11/23 15:05
 * @Param:
 * @Return:
 **/
public class DailyFileUtil {

    // 遍歷目錄(遞歸
    public static String folderMethod2(String path) {
        File file = new File (path);

        String fileNames = "";
        if (file.exists ( )) {
            File[] files = file.listFiles ( );
            if (null != files) {
                for (File file2 : files) {
                    if (file2.isDirectory ( )) {
                        System.out.println ("文件夾:" + file2.getAbsolutePath ( ));
                        folderMethod2 (file2.getAbsolutePath ( ));
                    } else {
                        fileNames += file2.getName ( ) + ",";
                        System.out.println ("文件:" + file2.getAbsolutePath ( ));
                    }
                }
            }
        } else {
            System.out.println ("文件不存在!");
        }
        return fileNames;
    }

    public static void fileToZip(String filePath, ZipOutputStream zipOut) throws IOException {
        // 需要壓縮的文件
        File file = new File (filePath);
        // 獲取文件名稱,如果有特殊命名需求,可以將參數列表拓展,傳fileName
        String fileName = file.getName ( );
        FileInputStream fileInput = new FileInputStream (filePath);
        // 緩沖
        byte[] bufferArea = new byte[1024 * 10];
        BufferedInputStream bufferStream = new BufferedInputStream (fileInput, 1024 * 10);
        // 將當前文件作為一個zip實體寫入壓縮流,fileName代表壓縮文件中的文件名稱
        zipOut.putNextEntry (new ZipEntry (fileName));
        int length = 0;
        // 最常規IO操作,不必緊張
        while ((length = bufferStream.read (bufferArea, 0, 1024 * 10)) != -1) {
            zipOut.write (bufferArea, 0, length);
        }
        //關閉流
        fileInput.close ( );
        // 需要注意的是緩沖流必須要關閉流,否則輸出無效
        bufferStream.close ( );
        // 壓縮流不必關閉,使用完后再關
    }


    /**
     * 文件壓縮
     *
     * @param srcFile 目錄或者單個文件
     * @param zipFile 壓縮后的ZIP文件
     */
    public static void doCompress(File srcFile, File zipFile) throws IOException {
        ZipOutputStream out = null;
        try {
            out = new ZipOutputStream (new FileOutputStream (zipFile));
            doCompress (srcFile, out);
        } catch (Exception e) {
            throw e;
        } finally {
            out.close ( );//記得關閉資源
        }
    }

    public static void doCompress(String filelName, ZipOutputStream out) throws IOException {
        doCompress (new File (filelName), out);
    }

    public static void doCompress(File file, ZipOutputStream out) throws IOException {
        doCompress (file, out, "");
    }

    public static void doCompress(File inFile, ZipOutputStream out, String dir) throws IOException {
        if (inFile.isDirectory ( )) {
            File[] files = inFile.listFiles ( );
            if (files != null && files.length > 0) {
                for (File file : files) {
                    String name = inFile.getName ( );
                    if (!"".equals (dir)) {
                        name = dir + "/" + name;
                    }
                    DailyFileUtil.doCompress (file, out, name);
                }
            }
        } else {
            DailyFileUtil.doZip (inFile, out, dir);
        }
    }

    public static void doZip(File inFile, ZipOutputStream out, String dir) throws IOException {
        String entryName = null;
        if (!"".equals (dir)) {
            entryName = dir + "/" + inFile.getName ( );
        } else {
            entryName = inFile.getName ( );
        }
        ZipEntry entry = new ZipEntry (entryName);
        out.putNextEntry (entry);

        int len = 0;
        byte[] buffer = new byte[1024];
        FileInputStream fis = new FileInputStream (inFile);
        while ((len = fis.read (buffer)) > 0) {
            out.write (buffer, 0, len);
            out.flush ( );
        }
        out.closeEntry ( );
        fis.close ( );
    }

    // 工具api(重載復用)
    public static boolean createFileOrDir(String path) {
        return createFileOrDir (new File (path));
    }

    // 沒有文件則創建
    private static boolean createFileOrDir(File file) {
        if (file.isDirectory ( )) {
            return file.mkdirs ( );
        }
        File parentFile = file.getParentFile ( );
        if (!parentFile.exists ( )) {
            System.out.println (parentFile.getPath ( ));
            boolean mkdirs = parentFile.mkdirs ( );
            if (!mkdirs)
                return false;
        } else {
            if (!parentFile.isDirectory ( )) {
                boolean delete = parentFile.delete ( );
                boolean mkdirs = parentFile.mkdirs ( );
                if (!delete || !mkdirs) return false;
            }
        }
        try {
            return file.createNewFile ( );
        } catch (IOException e) {
            e.printStackTrace ( );
        }
        return false;
    }
}

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,606評論 6 533
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,582評論 3 418
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,540評論 0 376
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,028評論 1 314
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,801評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,223評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,294評論 3 442
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,442評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,976評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,800評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,996評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,543評論 5 360
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,233評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,662評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,926評論 1 286
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,702評論 3 392
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,991評論 2 374

推薦閱讀更多精彩內容