代码改变世界

工具类

2022-03-19 15:51  通往神之路  阅读(43)  评论(0编辑  收藏  举报
private List<String> getPeriodList(Date priceDateStart, Date priceDateEnd){
        //期间拆分
        List<String> periodList = new ArrayList();
        String oldDateStartYear = DateUtil.formatDateTime(priceDateStart).substring(0, 4);
        String oldDateEndYear = DateUtil.formatDateTime(priceDateEnd).substring(0, 4);
        //
        String oldDateStartMonth = DateUtil.formatDateTime(priceDateStart).substring(5, 7);
        String oldDateEndMonth = DateUtil.formatDateTime(priceDateEnd).substring(5, 7);
        //
        String oldDateStartDay = DateUtil.formatDateTime(priceDateStart).substring(8, 10);
        String oldDateEndDay = DateUtil.formatDateTime(priceDateEnd).substring(8, 10);
        // 年相差
        Integer intOldDateStartYear = Integer.valueOf(oldDateStartYear);
        int y =  Integer.valueOf(oldDateEndYear) -  intOldDateStartYear;
        Integer intOldDateStartMonth = Integer.valueOf(oldDateStartMonth);
        Integer intOldDateEndMonth = Integer.valueOf(oldDateEndMonth);

        // 总的月相差
        int i2 = (intOldDateEndMonth + y * 12) - intOldDateStartMonth;
        int m2 = 0;
        int n2 = 0;
        for (int j2 = 0; j2 <= i2; j2++) {
            // 月份=13,年份加一
            n2 = intOldDateStartMonth + j2;
            if (n2<13) {
            m2 = n2;    
            }
            if (13 == intOldDateStartMonth + j2 || 25 == intOldDateStartMonth + j2  || 37 == intOldDateStartMonth + j2 || 49 == intOldDateStartMonth + j2) {
                intOldDateStartYear = intOldDateStartYear + 1;
                m2 = 0;
            }
            // 处理月份
            if (13 <= intOldDateStartMonth + j2) {
                m2++;
            }
            
            //这里分为四种情况,开始一批次,结束为一批次。开始一批次,结束为二批次。开始二批次,结束为一批次。开始二批次,结束为二批次
            // 开始日期属于一批次
            if (Integer.valueOf(oldDateStartDay) < 15) {
                // 结束日期属于一批次
                if (Integer.valueOf(oldDateEndDay) < 25) {
                    //i>0表示有多月份,所以最后一月是一批次
                    if (i2>0) {
                        //是否是最后一个月份
                        if (j2 == i2) {
                            periodList.add(intOldDateStartYear + "" + m2 + "一");
                        }else {
                            periodList.add(intOldDateStartYear + "" + m2 + "一");
                            periodList.add(intOldDateStartYear + "" + m2 + "二");    
                        }
                        
                    }else {
                        periodList.add(intOldDateStartYear + "" + m2 + "一");
                    }
                    
                } else {
                    // 结束日期属于二批次
                    periodList.add(intOldDateStartYear + "" + m2 + "一");
                    periodList.add(intOldDateStartYear + "" + m2 + "二");
                }

            } else {
                //第一个批次为二批次,
                if (Integer.valueOf(oldDateStartDay) > 15) {
                    //最后一个批次为二批次
                    if (Integer.valueOf(oldDateEndDay) > 25) {
                        //i>0表示有多月份,所以最后一月是两个批次
                        if (i2>0) {
                            if (j2==0) {
                                periodList.add(intOldDateStartYear + "" + m2 + "二");
                            }else {
                                periodList.add(intOldDateStartYear + "" + m2 + "一");
                                periodList.add(intOldDateStartYear + "" + m2 + "二");
                            }

                        }else {
                            periodList.add(intOldDateStartYear + "" + m2 + "二");
                        }
                        
                    }else {
                    //最后一个批次为一批次    
                        //i>0表示有多月份,所以最后一月是一批次
                        //是否是最后一个月份
                            if (j2 == i2) {
                                periodList.add(intOldDateStartYear + "" + m2 + "一");
                            }else {
                                //第一次
                                if (j2==0) {
                                    periodList.add(intOldDateStartYear + "" + m2 + "二");    
                                }else {
                                    periodList.add(intOldDateStartYear + "" + m2 + "一");
                                    periodList.add(intOldDateStartYear + "" + m2 + "二");
                                }
                            }
                            
                    }
                        
                }
            }
            
        }
        
        return periodList;
    }
期间拆分
/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.changan.contract.utils.excel;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Comment;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.changan.anywhere.common.utils.Encodes;
import com.changan.anywhere.common.utils.Reflections;
import com.changan.contract.utils.ExcelException;
import com.changan.contract.utils.excel.annotation.ExcelField;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;


/**
 * 导出Excel文件(导出“XLSX”格式,支持大数据量导出 )
 * @author hy
 * @version 2018-07-12
 */
public class ExportExcel {
    
    private static Logger log = LoggerFactory.getLogger(ExportExcel.class);
            
    /**
     * 工作薄对象
     */
    private SXSSFWorkbook wb;
    
    /**
     * 工作表对象
     */
    private Sheet sheet;
    
    /**
     * 样式列表
     */
    private Map<String, CellStyle> styles = Maps.newHashMap();
    
    /**
     * 当前行号
     */
    private int rownum;
    
    
    /**
     * 注解列表(Object[]{ ExcelField, Field/Method })
     */
    List<Object[]> annotationList = Lists.newArrayList();
    
    /**
     * 构造函数
     * @param title 表格标题,传“空值”,表示无标题
     * @param cls 实体对象,通过annotation.ExportField获取标题
     * @param sheetName 工作簿名称
     */
    public ExportExcel(String title, Class<?> cls,String sheetName){
        this(title, cls,sheetName,1);
    }
    
    /**
     * 构造函数
     * @param title 表格标题,传“空值”,表示无标题
     * @param cls 实体对象,通过annotation.ExportField获取标题
     * @param type 导出类型(1:导出数据;2:导出模板)
     */
    public ExportExcel(String title, Class<?> cls,String sheetName, int type){
        // Get annotation field 
        Field[] fs = cls.getDeclaredFields();
        for (Field f : fs){
            ExcelField ef = f.getAnnotation(ExcelField.class);
            if (ef != null && (ef.type()==0 || ef.type()==type)){
                annotationList.add(new Object[]{ef, f});
            }
        }
        // Get annotation method
        Method[] ms = cls.getDeclaredMethods();
        for (Method m : ms){
            ExcelField ef = m.getAnnotation(ExcelField.class);
            if (ef != null && (ef.type()==0 || ef.type()==type)){
                annotationList.add(new Object[]{ef, m});
            }
        }
        Field[] superfs = cls.getSuperclass().getDeclaredFields();
        for (Field f : superfs){
            ExcelField ef = f.getAnnotation(ExcelField.class);
            if (ef != null && (ef.type()==0 || ef.type()==type)){
                    annotationList.add(new Object[]{ef, f});
            }
        }
        // Get annotation method
        Method[] superms = cls.getSuperclass().getDeclaredMethods();
        for (Method m : superms){
            ExcelField ef = m.getAnnotation(ExcelField.class);
            if (ef != null && (ef.type()==0 || ef.type()==type)){
                annotationList.add(new Object[]{ef, m});
            }
        }
        // Field sorting
        annotationList.sort((o1,o2) -> ((ExcelField) o1[0]).sort()-((ExcelField) o2[0]).sort());
        // Initialize
        List<String> headerList = Lists.newArrayList();
        for (Object[] os : annotationList){
            String t = ((ExcelField)os[0]).title();
            // 如果是导出,则去掉注释
            if (type==1){
                String[] ss = StringUtils.split(t, "**", 2);
                if (ss.length==2){
                    t = ss[0];
                }
            }
            headerList.add(t);
        }
        initialize(title, headerList,sheetName);
    }
    
    /**
     * 构造函数
     * @param title 表格标题,传“空值”,表示无标题
     * @param headers 表头数组
     */
    public ExportExcel(String title, String[] headers,String sheetName) {
        initialize(title, Lists.newArrayList(headers),sheetName);
    }
    
    /**
     * 构造函数
     * @param title 表格标题,传“空值”,表示无标题
     * @param headerList 表头列表
     */
    public ExportExcel(String title, List<String> headerList,String sheetName) {
        initialize(title, headerList,sheetName);
    }
    
    /**
     * 初始化函数
     * @param title 表格标题,传“空值”,表示无标题
     * @param headerList 表头列表
     */
    private void initialize(String title, List<String> headerList,String sheetName) {
        this.wb = new SXSSFWorkbook(500);
        this.sheet = wb.createSheet(sheetName);
        // Create title
        if (StringUtils.isNotBlank(title)){
            Row titleRow = sheet.createRow(rownum++);
            titleRow.setHeightInPoints(30);
            Cell titleCell = titleRow.createCell(0);
            titleCell.setCellValue(title);
            sheet.addMergedRegion(new CellRangeAddress(titleRow.getRowNum(),
                    titleRow.getRowNum(), titleRow.getRowNum(), headerList.size()-1));
        }
        // Create header
        if (headerList == null){
            throw new ExcelException("headerList not null!");
        }
        Row headerRow = sheet.createRow(rownum++);
        headerRow.setHeightInPoints(16);
        for (int i = 0; i < headerList.size(); i++) {
            Cell cell = headerRow.createCell(i);
            String[] ss = StringUtils.split(headerList.get(i), "**", 2);
            if (ss.length==2){
                cell.setCellValue(ss[0]);
                Comment comment = this.sheet.createDrawingPatriarch().createCellComment(
                        new XSSFClientAnchor(0, 0, 0, 0, (short) 3, 3, (short) 5, 6));
                comment.setString(new XSSFRichTextString(ss[1]));
                cell.setCellComment(comment);
            }else{
                cell.setCellValue(headerList.get(i));
            }
        }
        for (int i = 0; i < headerList.size(); i++) {  
            int colWidth = sheet.getColumnWidth(i)*2;
            sheet.setColumnWidth(i, colWidth < 3000 ? 3000 : colWidth);  
        }
        log.debug("Initialize success.");
    }
    

    /**
     * 添加一行
     * @return 行对象
     */
    public Row addRow(){
        return sheet.createRow(rownum++);
    }
    

    /**
     * 添加一个单元格
     * @param row 添加的行
     * @param column 添加列号
     * @param val 添加值
     * @return 单元格对象
     */
    public Cell addCell(Row row, int column, Object val){
        return this.addCell(row, column, val, Class.class);
    }
    
    /**
     * 添加一个单元格
     * @param row 添加的行
     * @param column 添加列号
     * @param val 添加值
     * @return 单元格对象
     */
    public Cell addCell(Row row, int column, Object val, Class<?> fieldType){
        Cell cell = row.createCell(column);
        String cellFormatString = "@";
        try {
            if(val == null){
                cell.setCellValue("");
            }else if(fieldType != Class.class){
                cell.setCellValue((String)fieldType.getMethod("setValue", Object.class).invoke(null, val));
            }else{
                if(val instanceof String) {
                    cell.setCellValue((String) val);
                }else if(val instanceof Integer) {
                    cell.setCellValue((Integer) val);
                    cellFormatString = "0";
                }else if(val instanceof Long) {
                    cell.setCellValue((Long) val);
                    cellFormatString = "0";
                }else if(val instanceof Double) {
                    cell.setCellValue((Double) val);
                    cellFormatString = "0.00";
                }else if(val instanceof BigDecimal) {
                    cell.setCellValue(val.toString());
                    cellFormatString = "0.00";
                }else if(val instanceof Float) {
                    cell.setCellValue((Float) val);
                    cellFormatString = "0.00";
                }else if(val instanceof Date) {
                    cell.setCellValue((Date) val);
                    cellFormatString = "yyyy-MM-dd HH:mm";
                }else {
                    cell.setCellValue((String)Class.forName(this.getClass().getName().replaceAll(this.getClass().getSimpleName(), 
                        "fieldtype."+val.getClass().getSimpleName()+"Type")).getMethod("setValue", Object.class).invoke(null, val));
                }
            }
            if (val != null){
                CellStyle style = styles.get("data_column_"+column);
                if (style == null){
                    style = wb.createCellStyle();
                    style.setDataFormat(wb.createDataFormat().getFormat(cellFormatString));
                    styles.put("data_column_" + column, style);
                }
                cell.setCellStyle(style);
            }
        } catch (Exception ex) {
            log.error("Set cell value ["+row.getRowNum()+","+column+"] error: ",ex);
            if(val!=null){
                cell.setCellValue(val.toString());
            }    
        }
        return cell;
    }

    /**
     * 添加数据(通过annotation.ExportField添加数据)
     * @return list 数据列表
     */
    public <E> ExportExcel setDataList(List<E> list){
        for (E e : list){
            int colunm = 0;
            Row row = this.addRow();
            StringBuilder sb = new StringBuilder();
            for (Object[] os : annotationList){
                ExcelField ef = (ExcelField)os[0];
                Object val = null;
                // Get entity value
                try{
                    if (StringUtils.isNotBlank(ef.value())){
                        val = Reflections.invokeGetter(e, ef.value());
                    }else if (os[1] instanceof Field){
                            val = Reflections.invokeGetter(e, ((Field)os[1]).getName());
                    }else if (os[1] instanceof Method){
                            val = Reflections.invokeMethod(e, ((Method)os[1]).getName(), new Class[] {}, new Object[] {});
                 }
                }catch(Exception ex) {
                    // Failure to ignore
                    log.error(ex.getMessage(), ex);
                    val = "";
                }
                this.addCell(row, colunm++, val,ef.fieldType());
                sb.append(val + ", ");
            }
        }
        return this;
    }
    
    /**
     * 输出数据流
     * @param os 输出数据流
     */
    public ExportExcel write(OutputStream os) throws IOException{
        wb.write(os);
        return this;
    }
    
    /**
     * 输出到客户端
     * @param fileName 输出文件名
     */
    public ExportExcel write(HttpServletResponse response, String fileName) throws IOException{
        response.reset();
        response.setContentType("application/octet-stream; charset=utf-8");
        response.setHeader("Content-Disposition", "attachment; filename="+Encodes.urlEncode(fileName));
        write(response.getOutputStream());
        return this;
    }
    
    /**
     * 输出到文件
     * @param fileName 输出文件名
     */
    public ExportExcel writeFile(String name) throws IOException{
        FileOutputStream os = new FileOutputStream(name);
        this.write(os);
        return this;
    }
    
    /**
     * 清理临时文件
     */
    public ExportExcel dispose(){
        wb.dispose();
        return this;
    }
    
    /**
     * 返回SXSSFWorkbook
     */
    public SXSSFWorkbook getSXSSFWorkbook(){
        return     wb;
    }
    
    /**
     * 生成excel到指定路径
     * @param wb
     * @param path
     * @throws Exception
     */
    public void generateExcelToPath(String path) throws Exception {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(path);
            wb.write(fos);
        } finally {
            if (fos != null) {
                fos.flush();
                fos.close();
            }
            if (wb != null) {
                wb.close();
            }
        }
    }

}
ExportExcel
package com.changan.contract.utils.excel;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.util.CellRangeAddress;

public class ExportExcelUtil {
    //文档对象
    private HSSFWorkbook wb;
    //表格对象
    HSSFSheet sheet;
    //就算创建的行
    private int index = 0;
    //表格线粗细,0为细线,1为粗线
    private int borderType = 0;
    
    /**
     * 十实例化是给如表格名
     * @param sheetName
     */
    public ExportExcelUtil(String sheetName) {
        wb = new HSSFWorkbook();
        sheet = wb.createSheet(sheetName);
    }
    
    /**
     * 设置列宽
     * @param size
     */
    public void setColumnSize(int[] size) {
        for (int i = 0; i < size.length; i++) {
            sheet.setColumnWidth(i, size[i]*256);
        }
    }
    
    /**
     * 创建多表格头
     * @param rowNames 表格标题名称  格式如 {["name1","name2"],["name1","name2"]}
     * @param fontSize 字体大小
     * @param mergeRs 合并的单元格式 格式如[{"beginR":"行开始","endR":"行结束","beginC":"列开始","endC":"列开始"}] {}中为map,[]为list
     */
    public void setTableMultiCell(List<String[]> rowNames,short fontSize,List<Map<String, Integer>> mergeRs){
        List<Integer> indexList = new ArrayList<Integer>();//存放行坐标
        List<HSSFRow> HSSFRowList = new ArrayList<HSSFRow>();//存放行对象
        for (int i = 0; i < rowNames.size(); i++) {
            indexList.add(index++);
            HSSFRowList.add(sheet.createRow(indexList.get(i)));
        }
        
        HSSFCellStyle style = wb.createCellStyle();
        style.setWrapText(true);//自动换行
        //设置字体居中
        style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);//垂直居中
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        //设置边框
        if(0 == borderType){
            //设置细线边框
            style.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框    
            style.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框    
            style.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框    
            style.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框
        }else{
            //设置粗线边框
            style.setBorderBottom(HSSFCellStyle.BORDER_MEDIUM); //下边框    
            style.setBorderLeft(HSSFCellStyle.BORDER_MEDIUM);//左边框    
            style.setBorderTop(HSSFCellStyle.BORDER_MEDIUM);//上边框    
            style.setBorderRight(HSSFCellStyle.BORDER_MEDIUM);//右边框
        }
        //设置字体
        HSSFFont font = (HSSFFont) wb.createFont();
        font.setFontHeightInPoints(fontSize);
//        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//字体加粗
        style.setFont(font);
        //创建单元格
        HSSFCell cell;
        //创建单元格数据
        for (int i = 0; i < rowNames.size(); i++) {
            String[] rowNmae = rowNames.get(i);//获取行名数组
            for (int j = 0; j < rowNmae.length; j++) {
                cell = HSSFRowList.get(i).createCell(j);
                cell.setCellStyle(style);
                if(!"".equals(rowNmae[j])){
                    cell.setCellValue(rowNmae[j]);
                }
                
            }
        }

        //合并单元格    
        for (int i = 0; mergeRs!=null && i < mergeRs.size(); i++) {
            Map<String, Integer> mergeR = mergeRs.get(i);
                sheet.addMergedRegion(new CellRangeAddress(indexList.get(mergeR.get("beginR")-1),
                        indexList.get(mergeR.get("endR")-1), mergeR.get("beginC")-1,mergeR.get("endC")-1));
        }
    }
    
    /**
     * 得到文档对象
     * @return HSSFWorkbook
     */
    public HSSFWorkbook getHSSFWorkbook(){
        return wb;
    }
    
}
ExportExcelUtil
package com.changan.contract.utils;

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

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.changan.anywhere.common.utils.DateUtils;
import com.changan.anywhere.common.utils.Encodes;

import org.apache.commons.codec.binary.Base64;


public class FileDownloadUtils {


        /**
         * 编译下载的文件名
         * @param filename
         * @param agent
         * @return
         * @throws IOException
         */
        public static String encodeDownloadFilename(String filename, String agent)throws IOException {
            if (agent.contains("Firefox")) { // 火狐浏览器
                filename = "=?UTF-8?B?"
                        + Base64.encodeBase64String(filename.getBytes("utf-8"))
                        + "?=";
                filename = filename.replaceAll("\r\n", "");
            } else { // IE及其他浏览器
                //filename = URLEncoder.encode(filename, "utf-8");
                filename = filename.replace("+"," ");
            }
            return filename;
        }

        /**
         * 创建文件夹;
         * @param path
         */
        public static void createFile(String path) {
            File file = new File(path);
            //判断文件是否存在;
            if (!file.exists()) {
                //创建文件;
                file.mkdirs();
            }
        }

        /**
         * 生成.zip文件;
         * @param path
         * @throws IOException
         */ 
        public static ZipOutputStream craeteZipPath(String path) throws IOException{
            FileInputStream fileInputStream = null;
            File file = new File(path+DateUtils.getYear()+".zip");
            try (ZipOutputStream zipOutputStream = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(file)))){
                File[] files = new File(path).listFiles();
                byte[] buf = new byte[1024];
                int len = 0;
                if(files!=null && files.length > 0){
                    for(File excelFile:files){
                        String fileName = excelFile.getName();
                        try {
                            fileInputStream = new FileInputStream(excelFile);
                             //放入压缩zip包中;
                            zipOutputStream.putNextEntry(new ZipEntry(path + "/"+fileName));
                            //读取文件;
                            while((len=fileInputStream.read(buf)) >0){
                                zipOutputStream.write(buf, 0, len);
                            }
                            //关闭;
                            zipOutputStream.closeEntry();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }finally {
                            if(fileInputStream != null){
                                fileInputStream.close();
                            }
                        }
                       
                        
                    }
                }
                return zipOutputStream;
            } finally {
                if(fileInputStream != null){
                    fileInputStream.close();
                }
            
            } 
            
        }


        /**
         * //压缩文件
         * @param srcfile   要压缩的文件数组
         * @param zipfile  生成的zip文件对象
         */
        public static void ZipFiles(java.io.File[] srcfile, File zipfile) throws Exception {
              FileInputStream in =  null;
            try ( FileOutputStream fos = new FileOutputStream(zipfile); 
                    ZipOutputStream out = new ZipOutputStream(fos)){
                byte[] buf = new byte[1024];
                ;
                for (int i = 0; i < srcfile.length; i++) {
                       try {
                    in = new FileInputStream(srcfile[i]);
                    out.putNextEntry(new ZipEntry(srcfile[i].getName()));
                    int len;
                    while ((len = in.read(buf)) > 0) {
                        out.write(buf, 0, len);
                    }
                    out.closeEntry();
                       } catch (IOException e) {
                            e.printStackTrace();
                        }finally {
                            if(in != null){
                                in.close();
                            }
                        }
                }
                   
            } finally {
                if(in != null){
                    in.close();
                }
            }
           
        }

        /**
         * 删除文件夹及文件夹下所有文件
         * @param dir
         * @return
         */
        public static boolean deleteDir(File dir) {
            if (dir == null || !dir.exists()){
                return true;
            }
            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();
        }
        
        /**
         * 将批量文件打包下载成zip
         * @param request
         * @param response
         * @param zipName     下载的zip名
         * @param files       要打包的批量文件
         * @param zipPath     生成的zip路径
         * @throws Exception
         */
        public static void downloadZip(HttpServletRequest request, HttpServletResponse response, String zipName, List<File> files, String zipPath)throws Exception {
            File srcfile[] = new File[files.size()];
            File zip = new File(zipPath);
            for (int i = 0; i < files.size(); i++) {
                srcfile[i] = files.get(i);
            }
            //生成.zip文件;
            FileInputStream inStream = null;
            ServletOutputStream os = null;
            try {
                //设置下载zip的头信息
                FileDownloadUtils.setZipDownLoadHeadInfo(response, request, zipName);
                os = response.getOutputStream();
                FileDownloadUtils.ZipFiles(srcfile, zip);
                inStream = new FileInputStream(zip);
                byte[] buf = new byte[4096];
                int readLength;
                while (((readLength = inStream.read(buf)) != -1)) {
                    os.write(buf, 0, readLength);
                }
            }  finally {
                if (inStream != null) {
                    inStream.close();
                }
                if (os != null) {
                    os.flush();
                    os.close();
                }
            }
        }
        
        /**
         * 设置下载zip的响应头信息
         * @param response
         * @param fileName 文件名
         * @param request
         * @throws IOException
         * @author zgd
         * @time 2018年6月25日11:47:07
         */
        public static void setZipDownLoadHeadInfo(HttpServletResponse response, HttpServletRequest request, String fileName) throws IOException {
            // 获取客户端浏览器的类型
           // String agent = request.getHeader("User-Agent");
            response.setContentType("application/octet-stream; charset=utf-8");
            // 表示不能用浏览器直接打开
            response.setHeader("Connection", "close");
            // 告诉客户端允许断点续传多线程连接下载
            response.setHeader("Accept-Ranges", "bytes");
            response.setHeader("Content-Disposition", "attachment; filename="+Encodes.urlEncode(fileName));
    

        }



}
FileDownloadUtils
/** 
 * Project Name:Contract 
 * File Name:DateUtil.java 
 * Package Name:com.changan.contract.utils 
 * Date:2017年7月25日上午10:39:36 
 * Copyright (c) 2017, wangwenpei All Rights Reserved. 
 * 
 */
package com.changan.contract.utils;


import java.sql.Timestamp;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.time.ZonedDateTime;
import java.util.Calendar;
import java.util.Date;

import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.lang3.time.DateFormatUtils;


/**
 * 工具类,用于时间转换
 * date: 2017年7月25日 上午10:39:36
 * 
 * @author wangwenpei
 * @version 1.0
 * @since JDK 1.8
 */

public class DateUtil extends org.apache.commons.lang3.time.DateUtils{
    
    private static String[] parsePatterns = {
        "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM", 
        "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
        "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};
    
    /**
     * 将ZonedDateTime转换为Timestamp对象
     * 
     * @param date
     *            处理日期和时间与相应的时区
     * @return Timestamp 时间戳
     */
    public static Timestamp dateToTimestamp(ZonedDateTime date) {
        Timestamp ts = Timestamp.valueOf(date.toLocalDateTime());

        return ts;
    }

    /**
     * 将Timestamp转换成String
     * 
     * @param ts
     *            时间戳
     * @return String 字符串
     */
    public static String timestampToString(Timestamp ts) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        return sdf.format(ts);
    }
    /**
     * 将Date转换成String yyyy年MM月dd日
     * 
     * @param d
     *            
     * @return String 字符串
     */
    public static String timeToString(Date d){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
        return sdf.format(d);
    }
    
    /**
     * 将Date转换成String yyyy年MM月dd日
     * 
     * @param d
     *            
     * @return String 字符串
     */
    public static String timeToString2(Date d){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(d);
    }

    public static String timeToString3(Date d){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(d);
    }

    /**
     * 将当前时间转换为String
     * 
     * @return String 格式为"yyyy-MM"字符串
     */
    public static String dateToString() {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        return sdf.format(date);

    }

    /**
     * 功能:得到当前月份月初 格式为:xxxx-yy-zz (eg: 2017-12-01)<br>
     * 
     * @return String
     * @author pure
     * @throws ParseException 
     */
    public static Date getEarly(Date date) throws ParseException {
        int year = date.getYear();
        int month = date.getMonth();
        String timeString = year + "-" + month + "-01 00:00:00";
        SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return formater.parse(timeString);
    }
    /**
     * 将字符转为Date
     * @param str
     * @return yyyy年MM月dd日 格式
     * @throws ParseException
     */
    public static Date stringToTime(String str) throws ParseException{
        SimpleDateFormat formater = new SimpleDateFormat("yyyy年MM月dd日");
        return formater.parse(str);
    }

    /**
     * 将字符转为Date
     * @param str
     * @return yyyy年MM月dd日 格式
     * @throws ParseException
     */
    public static Date strToTime(String str) throws ParseException{
        SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return formater.parse(str);
    }
    
    /**
     * 
     * @param yyyy-MM-dd
     * @return Date
     */
     public static Date strToDate(String strDate) {
             SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
             ParsePosition pos = new ParsePosition(0);
            Date strtodate = formatter.parse(strDate, pos);
             return strtodate;
     }
     
    /**
     * 
     * @param yyyy年MM月dd日
     * @return Date
     */
     public static Date strToDate2(String strDate) {
             SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日");
             ParsePosition pos = new ParsePosition(0);
            Date strtodate = formatter.parse(strDate, pos);
             return strtodate;
     }
     
     /**
     * 
     * @param yyyyMMdd
     * @return Date
     */
     public static Date strToDate3(String strDate) {
             SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
             ParsePosition pos = new ParsePosition(0);
            Date strtodate = formatter.parse(strDate, pos);
             return strtodate;
     }
     
    /**
     * 得到当前日期字符串 格式(yyyy-MM-dd)
     */
    public static String getDate() {
        return getDate("yyyy-MM-dd");
    }
    
    /**
     * 得到当前日期字符串 格式(yyyy-MM-dd) pattern可以为:"yyyy-MM-dd" "HH:mm:ss" "E"
     */
    public static String getDate(String pattern) {
        return DateFormatUtils.format(new Date(), pattern);
    }
    
    /**
     * 得到日期字符串 默认格式(yyyy-MM-dd) pattern可以为:"yyyy-MM-dd" "HH:mm:ss" "E"
     */
    public static String formatDate(Date date, Object... pattern) {
        String formatDate = null;
        if (pattern != null && pattern.length > 0) {
            formatDate = DateFormatUtils.format(date, pattern[0].toString());
        } else {
            formatDate = DateFormatUtils.format(date, "yyyy-MM-dd");
        }
        return formatDate;
    }
    
    /**
     * 得到日期时间字符串,转换格式(yyyy-MM-dd HH:mm:ss)
     */
    public static String formatDateTime(Date date) {
        return formatDate(date, "yyyy-MM-dd HH:mm:ss");
    }

    /**
     * 得到当前时间字符串 格式(HH:mm:ss)
     */
    public static String getTime() {
        return formatDate(new Date(), "HH:mm:ss");
    }

    /**
     * 得到当前日期和时间字符串 格式(yyyy-MM-dd HH:mm:ss)
     */
    public static String getDateTime() {
        return formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
    }

    /**
     * 得到当前年份字符串 格式(yyyy)
     */
    public static String getYear() {
        return formatDate(new Date(), "yyyy");
    }

    /**
     * 得到当前月份字符串 格式(MM)
     */
    public static String getMonth() {
        return formatDate(new Date(), "MM");
    }

    /**
     * 得到当天字符串 格式(dd)
     */
    public static String getDay() {
        return formatDate(new Date(), "dd");
    }

    /**
     * 得到当前星期字符串 格式(E)星期几
     */
    public static String getWeek() {
        return formatDate(new Date(), "E");
    }
    
    /**
     * 日期型字符串转化为日期 格式
     * { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", 
     *   "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm",
     *   "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm" }
     */
    public static Date parseDate(Object str) {
        if (str == null){
            return null;
        }
        try {
            return parseDate(str.toString(), parsePatterns);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 获取过去的天数
     * @param date
     * @return
     */
    public static long pastDays(Date date) {
        long t = new Date().getTime()-date.getTime();
        return t/(24*60*60*1000);
    }

    /**
     * 获取过去的小时
     * @param date
     * @return
     */
    public static long pastHour(Date date) {
        long t = new Date().getTime()-date.getTime();
        return t/(60*60*1000);
    }
    
    /**
     * 获取过去的分钟
     * @param date
     * @return
     */
    public static long pastMinutes(Date date) {
        long t = new Date().getTime()-date.getTime();
        return t/(60*1000);
    }
    
    /**
     * 转换为时间(天,时:分:秒.毫秒)
     * @param timeMillis
     * @return
     */
    public static String formatDateTime(long timeMillis){
        long day = timeMillis/(24*60*60*1000);
        long hour = (timeMillis/(60*60*1000)-day*24);
        long min = ((timeMillis/(60*1000))-day*24*60-hour*60);
        long s = (timeMillis/1000-day*24*60*60-hour*60*60-min*60);
        long sss = (timeMillis-day*24*60*60*1000-hour*60*60*1000-min*60*1000-s*1000);
        return (day>0?day+",":"")+hour+":"+min+":"+s+"."+sss;
    }
    
    /**
     * 获取两个日期之间的天数
     * 
     * @param before
     * @param after
     * @return
     */
    public static double getDistanceOfTwoDate(Date before, Date after) {
        long beforeTime = before.getTime();
        long afterTime = after.getTime();
        return (afterTime - beforeTime) / (double)(1000 * 60 * 60 * 24);
    }
    
    
    
    /**
     * 获取日期和当前日期之间的天数
     *
     * @param before
     * @return
     */
    public static double getDistanceOfTwoDate(String before) {
        Date date = parseDate(before);
        if(date != null) {
            long beforeTime = date.getTime();
            long afterTime = System.currentTimeMillis();
            return (afterTime - beforeTime) / (double)(1000 * 60 * 60 * 24);
        }else {
            return 0;
        }
    }
    
    /**
     * 得到日期时间字符串,转换格式(yyyy-MM-dd HH:mm:ss)
     */
    public static String formatDateFullTime(Date date) {
        return formatDate(date, "yyyyMMddHHmmssS");
    }
    
    
    /**
     * 得到日期时间字符串,转换格式(yyyy-MM-dd HH:mm:ss)
     */
    public static String addDays(String date,int amount) {
        return formatDate(addDays(parseDate(date), amount));
    }
    
    /**
     * 验证两个时间段是否有重叠的情况
     * 
     * @return true交叉; false未交叉
     */
    public static boolean validateOverlap(Date start1, Date end1, Date start2, Date end2) {
        if((start2.before(start1) || DateUtils.isSameDay(start2, start1))
                && (end2.after(end1) || DateUtils.isSameDay(end2, end1))) {
            return true;
        }
        if((start2.after(start1) || DateUtils.isSameDay(start2, start1))
                && (end2.before(end1) || DateUtils.isSameDay(end2, end1))) {
            return true;
        }
        if((start2.before(start1) || DateUtils.isSameDay(start2, start1))
                && (end2.after(start1) || DateUtils.isSameDay(end2, start1)) 
                && (end2.before(end1) || DateUtils.isSameDay(end2, end1))) {
            return true;
        }
        if((end2.after(end1) || DateUtils.isSameDay(end2, end1))
                && (start2.after(start1) || DateUtils.isSameDay(start2, start1))
                && (start2.before(end1) || DateUtils.isSameDay(start2, end1))) {
            return true;
        }
        return false;
    }

    /**
     * 根据时间判断起止日期是否在规定范围内
     * @param start
     * @param end
     * @author Panxp
     * @create 2018/11/1
     * @return int
     */
    public static boolean startAndEndValidation(String start, String end) {
        int year = Integer.parseInt(end.substring(0,4));
        int month = Integer.parseInt(end.substring(5,7));
        String dayStart = start.substring(8,10);
        String dayEnd = end.substring(8,10);
        String day = getLastDayOfMonth(year, month).substring(8,10);
        if((!"1".equals(dayStart) && !"01".equals(dayStart) && !"21".equals(dayStart)) || (!"20".equals(dayEnd) && !day.equals(dayEnd))
                || (!"28".equals(dayEnd) && !day.equals(dayEnd) && !"20".equals(dayEnd)) || (!"29".equals(dayEnd) && !day.equals(dayEnd) && !"20".equals(dayEnd))) {
            return true;
        }
        return false;
    }

    /**
     * 获取指定年月的最后一天
     * @param year
     * @param month
     * @author Panxp
     * @create 2018/11/1
     * @return String
     */
    public static String getLastDayOfMonth(int year, int month) {
        Calendar cal = Calendar.getInstance();
        // 清空缓存,处理2月的特殊情况
        cal.clear();
        //设置年份
        cal.set(Calendar.YEAR, year);
        //设置月份
        cal.set(Calendar.MONTH, month-1);
        //获取某月最大天数
        int lastDay = cal.getActualMaximum(Calendar.DATE);
        //设置日历中月份的最大天数
        cal.set(Calendar.DAY_OF_MONTH, lastDay);
        //格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(cal.getTime());
    }

    /**
     * 获取指定日期当月的最后一天
     *
     * @param date
     * @return
     */
    public static int getLastDayOfMonth(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, 1);
        calendar.set(Calendar.DAY_OF_MONTH, 0);
        SimpleDateFormat format = new SimpleDateFormat("dd");
        return Integer.parseInt(format.format(calendar.getTime()));
    }


    /**
     * 获取过去第几天的日期
     * @param date 日期
     * @param past 过去天数
     * @param pattern 返回格式
     * @return
     */
    public static String getPastDate(Date date, int past, String pattern) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - past);
        Date today = calendar.getTime();
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        String result = format.format(today);
        return result;
    }
    
    public static String turnDateString(String dateStr) throws ParseException {
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy年MM月dd日");
        Date date=format1.parse(dateStr);
        SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd");
        return format2.format(date);
    }
}
DateUtil

 

//交叉的期间
List<String> intersection = periodList.stream().filter(item -> exists.contains(item)).collect(toList());