zoukankan      html  css  js  c++  java
  • JavaWeb项目文件夹生成Zip压缩包并下载到本地

    1、FileToZip接口类

    /**
     *
     */
    package com.sale.util;


    import java.io.BufferedInputStream;  
    import java.io.BufferedOutputStream;  
    import java.io.File;  
    import java.io.FileInputStream;  
    import java.io.FileNotFoundException;  
    import java.io.FileOutputStream;  
    import java.io.IOException;  
    import java.util.zip.ZipEntry;  
    import java.util.zip.ZipOutputStream;  


    /**
     * 将文件夹下面的文件
     * 打包成zip压缩文件
     * @author Saffi
     * @date 2017-10-16
     */
    public final class FileToZip {  
     
        private FileToZip(){}  
          
        /**
         * 将存放在sourceFilePath目录下的源文件,打包成fileName名称的zip文件,并存放到zipFilePath路径下
         * @param sourceFilePath :待压缩的文件路径
         * @param zipFilePath :压缩后存放路径
         * @param fileName :压缩后文件的名称
         * @return
         * @throws IOException
         */  
        public static boolean fileToZip(String sourceFilePath,String zipFilePath,String fileName) throws IOException{  
            boolean flag = false;  
            File sourceFile = new File(sourceFilePath);  
            FileInputStream fis = null;  
            BufferedInputStream bis = null;  
            FileOutputStream fos = null;  
            ZipOutputStream zos = null;  
            
            if(sourceFile.exists() == false){  
                System.out.println("待压缩的文件目录:"+sourceFilePath+"不存在.");  
            }else{  
                try {  
                    File zipFile = new File(zipFilePath + "/" + fileName +".zip");  
                    if(zipFile.exists()){  
                        
                        System.out.println(zipFilePath + "目录下存在名字为:" + fileName +".zip" +"打包文件.");  
                    }else{  
                        File[] sourceFiles = sourceFile.listFiles();  
                        if(null == sourceFiles || sourceFiles.length<1){  
                            System.out.println("待压缩的文件目录:" + sourceFilePath + "里面不存在文件,无需压缩.");  
                        }else{  
                            
                            fos = new FileOutputStream(zipFile);  
                            zos = new ZipOutputStream(new BufferedOutputStream(fos));  
                            byte[] bufs = new byte[1024*10];  
                            for(int i=0;i<sourceFiles.length;i++){  
                                //创建ZIP实体,并添加进压缩包  
                                ZipEntry zipEntry = new ZipEntry(sourceFiles[i].getName());  
                                zos.putNextEntry(zipEntry);  
                                
                                //读取待压缩的文件并写进压缩包里  
                                fis = new FileInputStream(sourceFiles[i]);  
                                bis = new BufferedInputStream(fis, 1024*10);  
                                int read = 0;  
                                while((read=bis.read(bufs, 0, 1024*10)) != -1){  
                                    zos.write(bufs,0,read);  
                                }  
                                if(null != bis){
                                    bis.close();  
                                }
                            }  
                            flag = true;
                            if(null != zos){
                                zos.closeEntry();
                                zos.close();
                            }
                        }  
                    }  
                } catch (FileNotFoundException e) {  
                    e.printStackTrace();  
                    throw new RuntimeException(e);  
                } catch (IOException e) {  
                    e.printStackTrace();  
                    throw new RuntimeException(e);  
                } finally{  
                    //关闭流  
                    try {       
                        if(null != fis){
                            fis.close();
                        }            
                        if(null != fos){
                            fos.close();
                        }
                    } catch (IOException e) {  
                        e.printStackTrace();  
                        throw new RuntimeException(e);  
                    }  
                }  
            }  
            
            return flag;  
        }   
          

    2、调用接口实现生成压缩包并下载

    /**
             * 打包Zip并下载
             *
             */
            @RequestMapping("tevo_testzip.action")
            public void downloadZips(HttpServletRequest request,HttpServletResponse response) {

         //原文件地址
                    String sourceFilePath = request.getSession().getServletContext().getRealPath("")+"/download/goodsbarcode";  

         //生成Zip存放地址
                    String zipFilePath = request.getSession().getServletContext().getRealPath("")+"/download";  

          //文件名
                    String fileName = "goodsbarcode";  
                    
                    try {  
                         //调用FileToZip接口生成压缩包
                        boolean flag = FileToZip.fileToZip(sourceFilePath, zipFilePath, fileName);  
                        if(flag){  
                            System.out.println("文件打包成功!");  
                        }else{  
                            System.out.println("文件打包失败!");  
                        }  

          //Zip压缩包文件名
                        String fileNames = "goodsbarcode.zip";  
                        //Zip压缩包路径
                        String path = request.getSession().getServletContext().getRealPath("")+"/download/goodsbarcode.zip";  
                        File file = new File(path);  
                        if(file.length()<1||file==null){
                             System.out.println("文件不存在!");
                        }else{
                            response.setCharacterEncoding("UTF-8");  
                            response.setHeader("Content-Disposition",  
                                    "attachment; filename=" + new String(fileNames.getBytes("ISO8859-1"), "UTF-8"));  
                            response.setContentLength((int) file.length());  
                            response.setContentType("application/zip");// 定义输出类型  
                            FileInputStream fis = new FileInputStream(file);  
                            BufferedInputStream buff = new BufferedInputStream(fis);  
                            byte[] b = new byte[1024];// 相当于我们的缓存  
                            long k = 0;// 该值用于计算当前实际下载了多少字节  
                            OutputStream myout = response.getOutputStream();// 从response对象中得到输出流,准备下载  
                            // 开始循环下载  
                            while (k < file.length()) {  
                                int j = buff.read(b, 0, 1024);  
                                k += j;  
                                myout.write(b, 0, j);  
                            }  
                            // 刷新此输出流并强制将所有缓冲的输出字节被写出
                            myout.flush();  

           //关闭流
                            myout.close();
                            buff.close();
                            fis.close();

           //删除生成的压缩包文件
                            file.delete();  
                        }
                       
                       //删除项目文件夹下所有的图片
                        File filedel = new File(sourceFilePath);  
                       if (filedel.isDirectory()) { //如果path表示的是一个目录
                              
                                File[] fileList = filedel.listFiles();  
                                for (int i = 0; i < fileList.length; i++) {  
                                    File delfile = fileList[i];  
                                    if (!delfile.isDirectory()) {      //如果文件的不是一个目录,则删除    
                                        //删除文件
                                         delfile.delete();                             
                                    }
                                }  
                            }
                    } catch (Exception e) {  
                        e.printStackTrace();
                    }  
                  
    }       

  • 相关阅读:
    333333
    钢镚儿冲刺一周期第六天
    钢镚儿冲刺一周期第五天
    钢镚儿冲刺一周期第四天
    钢镚儿冲刺一周期第三天
    钢镚儿冲刺一周期第二天
    钢镚儿冲刺一周期第一天
    软件工程第九周总结
    CVPR论文的爬取
    构建之法读后感第五
  • 原文地址:https://www.cnblogs.com/shoose/p/7681003.html
Copyright © 2011-2022 走看看