Java将一个文件夹下多个文件压缩并下载(工作案例)

Java将一个文件下多个文件压缩并下载,文件夹目录如下:

Java将一个文件夹下多个文件压缩并下载(工作案例)_第1张图片

每个文件下都有文件,要求实现将文件夹"A2023001_检查"压缩成"A2023001.zip",如下截图:

Java将一个文件夹下多个文件压缩并下载(工作案例)_第2张图片

 工具类ZipUtils:

public class ZipUtils {

    /**
     * 压缩一个文件或者目录
     *
     * @param zipFileName 压缩后的文件名(绝对路径):
     *                    如E:\app_data\upload\temp\batchDownload\A2023001_检查.zip
     * @param zipFilePath 需要被压缩的文件路径(绝对路径):
     *                    如E:\app_data\upload\temp\batchDownload\A2023001_检查
     * @throws Exception
     */
    public static void zip(String zipFileName, String zipFilePath) throws Exception {
        zip(zipFileName, new File(zipFilePath));
    }

    /**
     * @param zipFileName 压缩后的文件名及路径
     * @param zipFilePath   要被压缩的文件的输入流
     * @throws Exception
     */
    public static void zip(String zipFileName, File zipFilePath) throws Exception {
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));
        zip(out, zipFilePath, "");
        System.out.println("zip done");
        out.close();
    }

    /**
     * 用于压缩整个目录或者单个文件
     *
     * @param out  源文件的输出流
     * @param f    目标压缩文件的输入流
     * @param base a
     * @throws Exception
     */
    private static void zip(ZipOutputStream out, File f, String base) throws Exception {
        System.out.println("Zipping  " + f.getName());
        if (f.isDirectory()) {
            File[] fl = f.listFiles();
            //out.putNextEntry(new ZipEntry(base+"/"));
            out.putNextEntry(new org.apache.tools.zip.ZipEntry(base + f.getName() + "/"));
            for (int i = 0; i < fl.length; i++) {
                //zip(out,fl[i],base);
                zip(out, fl[i], base + f.getName() + "/");
            }
        } else {
            //base=base.length()==0?"":base+"/";
            out.putNextEntry(new org.apache.tools.zip.ZipEntry(base + f.getName()));
            FileInputStream in = new FileInputStream(f);
            int len;
            byte[] buffer = new byte[1024];
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            in.close();
        }
    }

    /**
     * 解压缩
     *
     * @param zipFileName     压缩文件
     * @param outputDirectory 目标路径
     * @throws Exception
     */
    public static void unzip(String zipFileName, String outputDirectory) throws Exception {
        ZipInputStream in = new ZipInputStream(new FileInputStream(zipFileName));
        ZipEntry z;
        while ((z = in.getNextEntry()) != null) {
            System.out.println("unziping " + z.getName());
            if (z.isDirectory()) {
                String name = z.getName();
                name = name.substring(0, name.length() - 1);
                File f = new File(outputDirectory + File.separator + name);
                f.mkdir();
                System.out.println("mkdir " + outputDirectory + File.separator + name);
            } else {
                File f = new File(outputDirectory + File.separator + z.getName());
                f.createNewFile();
                FileOutputStream out = new FileOutputStream(f);
                int b;
                while ((b = in.read()) != -1){
                    out.write(b);
                }
                out.close();
            }
        }
        in.close();
    }

    //测试压缩文件
    public static void main(String[] args) throws Exception {
        String zipFileName="E:\\app_data\\upload\\temp\\batchDownload\\A2023001_检查.zip";
        String zipFilePath="E:\\app_data\\upload\\temp\\batchDownload\\A2023001_检查";
        zip(zipFileName,zipFilePath);
    }
}

 实际工作中运用调用如下:

/**
     * 附件批量下载:打zip包
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/batchDownLoad.do")
    public void batchDownLoad(HttpServletRequest request, HttpServletResponse response) {
        FileInputStream fis = null;
        OutputStream os = null;
        try {
            //设置页面静态文字中文编码
            response.setCharacterEncoding("UTF-8");
            //压缩目录:为了本地测试写了本地地址,实际工作中写服务器地址
            String dateDir = "E:\\app_data\\upload\\temp\\batchDownload\\";
			//压缩名:实际工作中写定义的压缩名如系统当前时间+6位随机数(zipDirName = DateUtils.getCurrYYYYMMDD() + "_" + RandomUtils.randomByNumber(6))
			String zipDirName = "A2023001_检查";
            //定义临时压缩文件名
            String zipName = zipDirName + ".zip";
            //下面建打zip包用的子目录:E:\\app_data\\upload\\temp\\batchDownload\\A2023001_检查\\
            String targetFilePath = dateDir + zipDirName + File.separator;
            //判断是否存在该临时目录,没有就建立
            File targetPath = new File(targetFilePath);
            if (!targetPath.exists()) {
                targetPath.mkdirs();
            }

            //压缩后的文件名路径:E:\\app_data\\upload\\temp\\batchDownload\\A2023001_检查.zip
            String downLoadFile = dateDir + zipDirName + ".zip";
            //压缩文件(调用工具类)
            ZipUtils.zip(downLoadFile, targetFilePath);
            //创建zip文件
            File file = new File(downLoadFile);
            fis = new FileInputStream(file);
            os = response.getOutputStream();

            zipName = new String(zipName.getBytes("UTF-8"), "ISO8859-1");//文件名解决中文乱码:该方法从浏览器下载中文名正常展示
            //重置,清除缓存
            response.reset();
            //附件下载且UTF-8编码
            response.setContentType("application/x-download;charset=UTF-8");
            //附件下载中文乱码问题:该方法从浏览器下载中文名正常展示
            response.addHeader("Content-Disposition", "attachment;filename=" + zipName);
            //附件下载文件长度
            response.addHeader("Content-Length", "" + (int) file.length());

            int len;
            byte[] buffer = new byte[8192];
            while ((len = fis.read(buffer)) > 0) {
                os.write(buffer, 0, len);
                os.flush();
            }
        } catch (Exception e) {
            e.getMessage();
            logger.error("附件下载失败!", e);
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                e.getMessage();
                logger.error("附件批量下载:打zip包IOException:{}", e);
            }
        }
    }

以上代码,实际工作中能够正常运用,调用压缩工具类主要是压缩后的文件名绝对地址,需要被压缩的文件绝对路径,最后创建压缩文件,输出流读取输出

你可能感兴趣的:(工作案例总结(勿删),java)