java下載打包成zip

隨筆

1、調(diào)用

    // 導(dǎo)出歸檔件
    // 若是沒(méi)有選中則導(dǎo)出全部,選中則按照選中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\\";// 統(tǒng)一文件夾地址
        
        if ( DailyUtil.isStringEmpty (fileIds)){// 不為空的逗號(hào)隔開(kāi)字符串,填充
            String[] split = fileIds.split (",");
            if (DailyUtil.isArray (split)){
                for (String pdfName : split) {
                    String filePath = url + pdfName+ ".pdf";// 組合的最終路徑
                    paths.add (filePath);
                }
            }
        }else {// 不選中則導(dǎo)出所有(遍歷整個(gè) 目錄)
            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) {
            // 創(chuàng)建臨時(shí)路徑,存放壓縮文件
            File dir = new File(url+"\\zip");
            if (!dir.exists()) {// 判斷目錄是否存在     
                dir.mkdir();
            }
            
            String zipFilePath = url+"\\zip\\myzip.zip";

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

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

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

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

            //下載完成之后,刪掉這個(gè)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);
        // 獲取文件名稱,如果有特殊命名需求,可以將參數(shù)列表拓展,傳fileName
        String fileName = file.getName ( );
        FileInputStream fileInput = new FileInputStream (filePath);
        // 緩沖
        byte[] bufferArea = new byte[1024 * 10];
        BufferedInputStream bufferStream = new BufferedInputStream (fileInput, 1024 * 10);
        // 將當(dāng)前文件作為一個(gè)zip實(shí)體寫(xiě)入壓縮流,fileName代表壓縮文件中的文件名稱
        zipOut.putNextEntry (new ZipEntry (fileName));
        int length = 0;
        // 最常規(guī)IO操作,不必緊張
        while ((length = bufferStream.read (bufferArea, 0, 1024 * 10)) != -1) {
            zipOut.write (bufferArea, 0, length);
        }
        //關(guān)閉流
        fileInput.close ( );
        // 需要注意的是緩沖流必須要關(guān)閉流,否則輸出無(wú)效
        bufferStream.close ( );
        // 壓縮流不必關(guān)閉,使用完后再關(guān)
    }


    /**
     * 文件壓縮
     *
     * @param srcFile 目錄或者單個(gè)文件
     * @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 ( );//記得關(guān)閉資源
        }
    }

    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(重載復(fù)用)
    public static boolean createFileOrDir(String path) {
        return createFileOrDir (new File (path));
    }

    // 沒(méi)有文件則創(chuàng)建
    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;
    }
}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容