java下载打包成zip

随笔

1、调用

    // 导出归档件
    // 若是没有选中则导出全部,选中则按照选中Laura
    public void plistDownLoad() throws Exception {
        String fileIds = request.getParameter ("fileIds");

        // 此处模拟处理ids,拿到文件下载url
        List 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;
    }
}

你可能感兴趣的:(java下载打包成zip)