栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java实现多个文件生成压缩包下载

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java实现多个文件生成压缩包下载

目录

1、工具类代码

2、FileInfo实体类

3、控制层调用代码


1、工具类代码
package com.shucha.digitalportal.biz.utils;


import com.shucha.digitalportal.biz.model.FileInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;

import java.io.*;
import java.util.List;

import static org.springframework.util.StreamUtils.BUFFER_SIZE;


@Slf4j
public class ZipUtils {

    
    public static void downloadZip(OutputStream outputStream, List fileList) throws IOException {
        try (ZipOutputStream zos = new ZipOutputStream(outputStream)) {
            zos.setEncoding("GBK");
            for (FileInfo fileInfo : fileList) {
                File file = new File(fileInfo.getFilePath());
                if (file.exists()) {
                    ZipEntry zipEntry = new ZipEntry(fileInfo.getFileName());
                    zos.putNextEntry(zipEntry);
                    byte[] buf = new byte[BUFFER_SIZE];
                    int len;
                    FileInputStream in = new FileInputStream(file);
                    while ((len = in.read(buf)) != -1) {
                        zos.write(buf, 0, len);
                        zos.flush();
                    }
                }
            }
            zos.flush();
        } catch (IOException e) {
            log.error("文件压缩异常:", e);
            throw e;
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                log.error("导出文件关闭流异常", e);
            }
        }
    }

    
    public static void downloadZipOldName(OutputStream outputStream, List fileList) throws IOException {
        try (ZipOutputStream zos = new ZipOutputStream(outputStream)) {
            zos.setEncoding("GBK");
            for (File file : fileList) {
                if (file.exists()) {
                    ZipEntry zipEntry = new ZipEntry(file.getName());
                    zos.putNextEntry(zipEntry);
                    byte[] buf = new byte[BUFFER_SIZE];
                    int len;
                    FileInputStream in = new FileInputStream(file);
                    while ((len = in.read(buf)) != -1) {
                        zos.write(buf, 0, len);
                        zos.flush();
                    }
                }
            }
            zos.flush();
        } catch (IOException e) {
            log.error("文件压缩异常:", e);
            throw e;
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                log.error("导出文件关闭流异常", e);
            }
        }
    }

    
    public static File zipCompress(File inputFile, boolean delFlag) throws Exception {
        File zipFile = null;
        //创建zip输出流
        //为了解决中文乱码的问题,ZipOutputStream用org.apache.tools.zip.*
        //不要用 java.util.zip.*
        if (inputFile != null && inputFile.exists()) {
            try {
                String path = inputFile.getCanonicalPath();
                String zipFileName = path + ".zip";
                zipFile = new File(zipFileName);
                if (zipFile.exists()) {
                    zipFile.delete();
                }
                zipFile.createNewFile();//创建文件
                try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile))){
                    //解决中文乱码问题,指定编码GBK
                    zos.setEncoding("GBK");
                    //压缩文件或文件夹
                    compressFile(zos, inputFile, inputFile.getName());
                }
            } catch (Exception e) {
                log.error("文件压缩异常:", e);
                throw e;
            } finally {
                if (delFlag) {
                    //递归删除源文件及源文件夹
                    deleteFile(inputFile);
                }
            }
        }
        return zipFile;
    }

    
    private static void compressFile(ZipOutputStream zos, File sourceFile, String baseName) throws Exception {
        if (!sourceFile.exists()) {
            return;
        }

        //若路径为目录(文件夹)
        if (sourceFile.isDirectory()) {
            //取出文件夹中的文件(或子文件夹)
            File[] fileList = sourceFile.listFiles();
            //若文件夹为空,则创建一个目录进入点
            if (fileList.length == 0) {
                //文件名称后跟File.separator表示这是一个文件夹
                zos.putNextEntry(new ZipEntry(baseName + File.separator));
                //若文件夹非空,则递归调用compressFile,对文件夹中的每个文件或每个文件夹进行压缩
            } else {
                for (int i = 0; i < fileList.length; i++) {
                    compressFile(zos, fileList[i],
                            baseName + File.separator + fileList[i].getName());
                }
            }

            //若为文件,则先创建目录进入点,再将文件写入zip文件中
        } else {
            ZipEntry ze = new ZipEntry(baseName);
            //设置ZipEntry的最后修改时间为源文件的最后修改时间
            ze.setTime(sourceFile.lastModified());
            zos.putNextEntry(ze);

            try (FileInputStream fis = new FileInputStream(sourceFile)) {
                copyStream(fis, zos);
            }
        }
    }

    
    private static void copyStream(InputStream in, OutputStream out) throws IOException {
        int bufferLength = 1024 * 100;
        synchronized (in) {
            synchronized (out) {
                int count = 0;
                byte[] buffer = new byte[bufferLength];
                while ((count = in.read(buffer, 0, bufferLength)) != -1) {
                    out.write(buffer, 0, count);
                }
                out.flush();
            }
        }
    }

    
    private static void deleteFile(File sourceFile) throws Exception {
        //如果路径为目录
        if (sourceFile.isDirectory()) {
            //取出文件夹中的文件或子文件夹
            File[] fList = sourceFile.listFiles();
            if (fList.length == 0) {
                sourceFile.delete();
            } else {
                for (int i = 0; i < fList.length; i++) {
                    deleteFile(fList[i]);
                }
                sourceFile.delete();
            }
            //如果为文件则直接删除
        } else {
            sourceFile.delete();
        }
    }
}

2、FileInfo实体类
package com.shucha.digitalportal.biz.model;

import java.util.Date;
import com.baomidou.mybatisplus.annotation.TableId;
import com.sdy.common.model.BaseModel;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.sdy.common.utils.DateUtil;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;


@Data
@EqualsAndHashCode(callSuper = true)
@Accessors(chain = true)
public class FileInfo extends BaseModel {
    private static final long serialVersionUID = 1L;

    
    @ApiModelProperty(value = "主键")
    @JsonSerialize(using = ToStringSerializer.class)
    @TableId
    private Long id;

    
    @ApiModelProperty(value = "数据主键ID")
    private Long dataId;

    
    @ApiModelProperty(value = "附件名称")
    private String fileName;

    
    @ApiModelProperty(value = "附件路径")
    private String filePath;

    
    @ApiModelProperty(value = "附件类型(1-通知公告,2-风险气象台)")
    private Integer fileType;

    
    @ApiModelProperty(value = "创建时间")
    @JsonFormat(pattern = DateUtil.DATETIME_FORMAT)
    private Date createTime;

    
    @ApiModelProperty(value = "更新时间")
    @JsonFormat(pattern = DateUtil.DATETIME_FORMAT)
    private Date updateTime;

}

3、控制层调用代码
@GetMapping(value = "/downFileZip")
    @ApiOperation(value = "多个附件,打包成zip压缩包下载")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "数据ID", required = true),
            @ApiImplicitParam(name = "fileType", value = "附件类型(1-通知公告)", required = true)
    })
    public void downFileZip(HttpServletResponse response, Long id, Integer fileType) throws Exception {
        Assert.isNull(id,"附件地址ID不能为空");
        Assert.isNull(fileType,"附件类型不能为空");
        OutputStream out = null;
        FileInputStream fis = null;
        //文件名
        String fileName = null;
        // 根据数据ID和附件类型 查询附件数据
        List list = fileInfoService.list(Wrappers.lambdaQuery()
                .eq(FileInfo::getDataId, id)
                .eq(FileInfo::getFileType,fileType));
        Assert.isTrue(list.size() ==0,"没有对应的附件可下载!");
        String oldFileName = list.get(0).getFileName();
        int t = oldFileName.lastIndexOf(".");
        fileName = t > 0 ? oldFileName.substring(0, t) : oldFileName;
        try {
            out = response.getOutputStream();
            // 附件文件放入文件list
            List fileList = new ArrayList<>();
            for(int i=0;i

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/955883.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号