java下载zip文件

基本功能:

第一种:

  E盘下某一个目录下所有文件以及文件夹打包下载

首先工具类   直接复制进去就好

  


public static void doCompress(String srcFile, String zipFile) throws IOException { doCompress(new File(srcFile), new File(zipFile)); } /** * 文件压缩 * @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; } FileUtil.doCompress(file, out, name); } } } else { FileUtil.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(); }

 测试:

打包 E:\testExport\export  以及下面所有子文件和文件夹  
@RequestMapping(params = { "*****" })
    public void exportShowPic(HttpServletRequest request,HttpServletResponse response) throws IOException {
         String zipName = "myfile.zip";
            response.setContentType("APPLICATION/OCTET-STREAM");  
            response.setHeader("Content-Disposition","attachment; filename="+zipName);
            ZipOutputStream out = new ZipOutputStream(response.getOutputStream());
            try {
              
                FileUtil.doCompress("E:\testExport\export", out);
                  response.flushBuffer();
            } catch (Exception e) {
                e.printStackTrace();
            }finally{
                out.close();
            }
    }

结果:下载成功 

以上是下载打包好的压缩文件   

第二种:

  将本地的文件直接打包到指定目录  不需要下载

还是先把方法给大家(也是copy的):

            /**
            * 压缩文件
            *
            * @param sourceFilePath 源文件路径
            * @param zipFilePath    压缩后文件存储路径
            * @param zipFilename    压缩文件名
            */
           public void compressToZip(String sourceFilePath, String zipFilePath, String zipFilename) {
               File sourceFile = new File(sourceFilePath);
               File zipPath = new File(zipFilePath);
               if (!zipPath.exists()) {
                   zipPath.mkdirs();
               }
               File zipFile = new File(zipPath + File.separator + zipFilename);
               try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile))) {
                   writeZip(sourceFile, "", zos);
                   //文件压缩完成后,删除被压缩文件
                  // boolean flag = deleteDir(sourceFile);
               } catch (Exception e) {
                   e.printStackTrace();
                   throw new RuntimeException(e.getMessage(), e.getCause());
               }
           }
           
           /**
            * 遍历所有文件,压缩
            *
            * @param file       源文件目录
            * @param parentPath 压缩文件目录
            * @param zos        文件流
            */
           public static void writeZip(File file, String parentPath, ZipOutputStream zos) {
               if (file.isDirectory()) {
                   //目录
                   parentPath += file.getName() + File.separator;
                   File[] files = file.listFiles();
                   for (File f : files) {
                       writeZip(f, parentPath, zos);
                   }
               } else {
                   //文件
                   try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) {
                       //指定zip文件夹
                       ZipEntry zipEntry = new ZipEntry(parentPath + file.getName());
                       zos.putNextEntry(zipEntry);
                       int len;
                       byte[] buffer = new byte[1024 * 10];
                       while ((len = bis.read(buffer, 0, buffer.length)) != -1) {
                           zos.write(buffer, 0, len);
                           zos.flush();
                       }
                   } catch (Exception e) {
                       e.printStackTrace();
                       throw new RuntimeException(e.getMessage(), e.getCause());
                   }
                   }
               }
           
           /**
            * 删除文件夹
            *
            * @param dir
            * @return
            */
           public static boolean deleteDir(File dir) {
               if (dir.isDirectory()) {
                   String[] children = dir.list();
                   for (int i = 0; i < children.length; i++) {
                       boolean success = deleteDir(new File(dir, children[i]));
                       if (!success) {
                           return false;
                       }
                   }
               }
               //删除空文件夹
               return dir.delete();
           }

然后测试:

@RequestMapping(params = { "****" })
    @ResponseBody
    public AjaxJson exportShowPic(HttpServletRequest request,HttpServletResponse response) throws IOException {
        AjaxJson ajaxJson = new AjaxJson();
        try {
            FileUtil fuUtil = new FileUtil();
            String planId = request.getParameter("id");
            System.out.println("planId"+planId);
            String sourceFilePath ="E:\testExport";
            String zipFilePath ="E:\11";
            String fileName = "test.zip";
            fuUtil.compressToZip(sourceFilePath, zipFilePath, fileName);
            
            
            String zipName = "myfile.zip";
            response.setContentType("APPLICATION/OCTET-STREAM");  
            response.setHeader("Content-Disposition","attachment; filename="+zipName);
            ZipOutputStream out = new ZipOutputStream(response.getOutputStream());
           
            
            ajaxJson.setSuccess(true);
            ajaxJson.setMsg("下载成功");
        } catch (Exception e) {
            ajaxJson.setSuccess(false);
            ajaxJson.setMsg("下载失败  联系管理员");
            e.printStackTrace();
        }
        return ajaxJson;
    }
原文地址:https://www.cnblogs.com/bdjsdl/p/13438257.html