【工具类】多文件压缩下载ZipUtil

2022-10-25 16:10:40 浏览数 (1)

ZipUtil

代码语言:javascript复制
import java.io.*;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletResponse;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
//import java.util.zip.ZipEntry;
//import java.util.zip.ZipOutputStream;

/**
 * 生成压缩文件工具类
 * @author 
 *
 */
public final class ZipUtil {

	private static Logger logger = LoggerFactory.getLogger(ZipUtil.class);
	/**
	 * 字节数组长度
	 */
	private static final int BYTE_ARRAY_LENGTH = 1024;
    
    
    private ZipUtil(){
        throw new IllegalStateException("ZipUtil class");
    }
    
	/**
	 * 创建目标路径中文件夹
	 * @param folderName 路径
	 * @return 创建结果
	 */
	public static boolean makeDirs(String folderName) {
		if (folderName == null || folderName.isEmpty()) {
			return false;
		}
		File folder = new File(folderName);
		return (folder.exists() && folder.isDirectory()) ? true : folder.mkdirs();
	}
	
	 /**
	  * 创建压缩文件  
	  * @param srcfile 源文件列表
	  * @param zipfile 压缩文件
	 * @throws IOException io异常
	  */
    public static void zipFiles(File[] srcfile, File zipfile) throws IOException {  
        byte[] buf = new byte[BYTE_ARRAY_LENGTH];  
        ZipOutputStream out =  null;
        FileInputStream in = null;
        try {  
        	out = new ZipOutputStream(new FileOutputStream(  
                    zipfile));  
            for (int i = 0; i < srcfile.length; i  ) {
                try{
					in = new FileInputStream(srcfile[i]);  
					out.putNextEntry(new ZipEntry(srcfile[i].getName()));  
					// 支持中文  解决文件名乱码问题
		            out.setEncoding("GBK");
					int len;  
					while ((len = in.read(buf)) > 0) {
					    out.write(buf, 0, len);  
					}
                }	
				catch (Exception e) {
				    logger.error(String.format("压缩文件出错 01:{}%s", e));
                }
				finally{
				    out.closeEntry();
				    in.close();
				}
            }  
        } catch (IOException e) {  
            logger.error(String.format("压缩文件出错 02:{}%s", e));
        }finally{
        	out.close();
        }
    } 
    
    /**
     * 从浏览器下载压缩文件
     * @param file 文件对象
     * @param response 响应对象
     * @param isDelete 是否删除源文件
     * @throws IOException io异常
     */
    public static void downloadZipFile(File file,HttpServletResponse response,boolean isDelete) throws IOException{
    	OutputStream toClient = null;
//		InputStream inputStream = null;
    	 try(InputStream inputStream =new FileInputStream(file);) {

             // 清空response
             response.reset();
             toClient = new BufferedOutputStream(response.getOutputStream());
//			 inputStream=new FileInputStream(file);
			 response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8");
			 response.setHeader("Content-Disposition", "attachment;filename="   URLEncoder.encode(file.getName(),"UTF-8"));
			 int len=0;
			 byte[] buffer=new byte[1024];
			 while((len=inputStream.read(buffer))>0){
				 toClient.write(buffer,0,len);
			 }
             toClient.flush();
          } catch (IOException ex) {
              logger.error(ex.getMessage());
         }
    	 finally{
        	 if(toClient!= null){
        		 toClient.close();
        	 }
//			 if(inputStream!= null){
//				 inputStream.close();
//			 }

         }
    	 //在所有流都关闭后再删除文件
        if(isDelete&&file.exists()&&(!file.delete())) {//是否将生成的服务器端文件删除
//            if (file.exists()) {
//                if (!file.delete()){
                    logger.error("删除失败");
//                }
//            }

        }
	}
}

使用实例:

代码语言:javascript复制
				//多个文件下载,需要压缩
                //导出文件路径
                String filePath = System.getProperty("catalina.base")   File.separator   "tmp\" getCurrentUser().getLoginId() "\";
                //创建此路径
                ZipUtil.makeDirs(filePath);
                //得到此路径下文件
                File fileDir = new File(filePath);
                File[] fileDirs = fileDir.listFiles();
                this.deleteFile(fileDirs);
                //导出Excel文件路径
                String fullFilePath = "";
                //用于存放生成的excel文件名称
                List<String> fileNameforexcel = new ArrayList<String>();
                //导出压缩文件路径
                String zipFilePath = "";
                //导出压缩文件的全路径
                String zipname = this.getZipName(pglx);
                zipFilePath = filePath   File.separator   zipname   ".zip";
                File zip = new File(zipFilePath);//创建压缩文件
                //保存文件名
                //String fileName = "";
                //FileOutputStream os = null;
                for (int i = 0; i < pgbgBeans.size(); i  ) {
                    PgbgBean pgbgBean = pgbgBeans.get(i);
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("pgjgzs", pgbgBean);
                    try {
                        String fileNametemp = "(" String.valueOf(i 1) ")"
                                 ExcelUtils.exportInspectionRecordSurface(request, response, map,pglx);
                        ExcelUtils.writeExcelTolocal(fileNametemp ".xls", filePath);
                        fullFilePath = filePath fileNametemp ".xls";
                        fileNameforexcel.add(fullFilePath);
                    } catch (Exception e) {
                    	log.error("批量文件下载异常", e);
                    }
                }

                //将excel文件生成压缩文件
                File[] srcfile = new File[fileNameforexcel.size()];
                for (int j = 0, n1 = fileNameforexcel.size(); j < n1; j  ) {
                    srcfile[j] = new File(fileNameforexcel.get(j));
                }
                try {
                    ZipUtil.zipFiles(srcfile, zip);
                } catch (IOException e) {
                	log.error("生成压缩文件异常", e);
                }

                File file = new File(zipFilePath);
                try {
                    ZipUtil.downloadZipFile(file, response, true);
                } catch (IOException e) {
                	log.error("压缩文件下载异常", e);
                }

ExcelUtils.writeExcelTolocal方法

代码语言:javascript复制
/**
     * 将excel导出到本地
     * @param fileName 文件名
     * @param pathname 路径名
     * @throws IOException io异常
     */
    public static void writeExcelTolocal(String fileName, String pathname) throws IOException {
        OutputStream out = null;
        try {
            out = new FileOutputStream(new File(pathname   fileName));
            workbook.write(out);
            //byte[] bytes = new byte[1024];
            //out.write(bytes, 0, bytes.length);
            out.flush();
        } catch (FileNotFoundException e) {
            logger.error("导出到本地文件不存在", e);
        } catch (IOException e) {
            logger.error("文件导出到本地异常", e);
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

0 人点赞