1. 程式人生 > 實用技巧 >java下載zip檔案

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;
    }