springboot多文件压缩

springboot多文件压缩

   项目要求需要将所有附件进行压缩,记录下步骤

环境依赖

我使用的时jdk8,基本已经包含了所有可用的包,但是若是又特殊要求需要用到的自行导入

实现步骤

直接贴代码吧,我在本地自己测试用,所以文件路径都是本地路径,记得修改

	// 多文件压缩为zip
    //多个文件,压缩成zip后下载
   public void downloadMoreFile(HttpServletResponse response) {

        String fileName1= "XXXXX\\Desktop\\2022.1fp\\1.xlsx";
        String fileName2= "XXXXX\\Desktop\\2022.1fp\\2.xlsx";
        // 创建文件对象
        File aFile= new File(fileName1);
        File bFile= new File(fileName2);
        // 构建文件集合,存放所有待压缩的文件
        List<File> files = new ArrayList<>();
        files.add(aFile);
        files.add(bFile);
        // 判断文件存在性,若不存在文件无法压缩
        if (aFile.exists() && bFile.exists()) {
            // 压缩包绝对路径
            String zipTmp = "XXXXXX\\Desktop\\2022.1fp\\2.zip";
            // 压缩
            zipd(zipTmp,files,response);
        }
    }

zipd实现内容

/**
     * 压缩
     * @param zipTmp 压缩包绝对路径
     * @param files  待压缩文件集合
     * @param response  http请求代表响应的对象
     */
    public void zipd(String zipTmp,List<File> files,HttpServletResponse response){
        // 创建压缩包文件对象
        File zipTmpFile = new File(zipTmp);
        try {
//            压缩包文件若已存在则删除原本的文件
            if (zipTmpFile.exists()) {
                zipTmpFile.delete();
            }
//            不存在新建压缩文件
            zipTmpFile.createNewFile();
//            去除jsp编译html首部的空白行。
            response.reset();
//            FileOutputStream字节输出流超类 文件输出流是用于将数据写入到输出流File或一个FileDescriptor
            // 创建文件输出流
            FileOutputStream fous = new FileOutputStream(zipTmpFile);
//            ZipOutputStream压缩流
//            此流用于以 ZIP 文件格式写入文件,包括对压缩和未压缩条目的支持,也就是把文件打包成压缩文件,常用于附件下载(多文件下载),文件压缩存储。
            ZipOutputStream zipOut = new ZipOutputStream(fous);
            // 循环处理待压缩文件
            int size = files.size();
            for (int i = 0; i < size; i++) {
                File file = files.get(i);
                // 将文件写入压缩流
                zipFile(file, zipOut);
            }
            // 关闭流
            zipOut.close();
            fous.close();
//            downloadZip(zipTmpFile, response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

zipFile实现内容

   /**
     *
     * @param inputFile 待压缩文件
     * @param ouputStream 压缩流
     */
    public void zipFile(File inputFile, ZipOutputStream ouputStream) {
        try {
            if (inputFile.exists()) {
                if (inputFile.isFile()) {
                    // 待压缩文件输入流
                    FileInputStream IN = new FileInputStream(inputFile);
//                    创建 BufferedInputStream具有指定缓冲区大小,并保存其参数,输入流 in ,供以后使用。
                    BufferedInputStream bins = new BufferedInputStream(IN, 512);
//                    ZipEnter:表示压缩文件的条目(文件目录)
                    ZipEntry entry = new ZipEntry(inputFile.getName());
                    // 在zip流中创建一个entry文件
                    ouputStream.putNextEntry(entry);

                    int nNumber;
                    byte[] buffer = new byte[512];
                    while ((nNumber = bins.read(buffer)) != -1) {
                        ouputStream.write(buffer, 0, nNumber);
                    }
                    // 关闭流
                    bins.close();
                    IN.close();
                } else {
                    // 处理文件夹的情况
                    try {
                        File[] files = inputFile.listFiles();
                        for (int i = 0; i < files.length; i++) {
                            zipFile(files[i], ouputStream);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

若需要下载,记得加后面的方法

public static HttpServletResponse downloadZip(File file, HttpServletResponse response) {
        if (file.exists() == false) {
            System.out.println("待压缩的文件目录:" + file + "不存在.");
        } else {
            try {
                // 以流的形式下载文件。
                InputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
                byte[] buffer = new byte[fis.available()];
                fis.read(buffer);
                fis.close();
                // 清空response
                response.reset();

                OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
                response.setContentType("application/octet-stream");

                // 如果输出的是中文名的文件,在此处就要用URLEncoder.encode方法进行处理
                response.setHeader("Content-Disposition",
                        "attachment;filename=" + new String(file.getName().getBytes("GB2312"), "ISO8859-1"));
                toClient.write(buffer);
                toClient.flush();
                toClient.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                try {
                    File f = new File(file.getPath());
                    f.delete();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return response;
    }
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot提供了一个非常方便的方式来压缩文件,可以使用Java自带的ZipOutputStream来实现。 你可以编写一个简单的工具类,将一个文件夹下的所有文件压缩成一个zip文件,代码如下: ```java import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class ZipUtils { public static void zipFolder(String srcFolder, String destZipFile) throws IOException { ZipOutputStream zip = null; FileOutputStream fileWriter = null; fileWriter = new FileOutputStream(destZipFile); zip = new ZipOutputStream(fileWriter); addFolderToZip("", srcFolder, zip); zip.flush(); zip.close(); } private static void addFileToZip(String path, String srcFile, ZipOutputStream zip) throws IOException { File folder = new File(srcFile); if (folder.isDirectory()) { addFolderToZip(path, srcFile, zip); } else { byte[] buf = new byte[1024]; int len; FileInputStream in = new FileInputStream(srcFile); zip.putNextEntry(new ZipEntry(path + "/" + folder.getName())); while ((len = in.read(buf)) > 0) { zip.write(buf, 0, len); } } } private static void addFolderToZip(String path, String srcFolder, ZipOutputStream zip) throws IOException { File folder = new File(srcFolder); for (String fileName : folder.list()) { if (path.equals("")) { addFileToZip(folder.getName(), srcFolder + "/" + fileName, zip); } else { addFileToZip(path + "/" + folder.getName(), srcFolder + "/" + fileName, zip); } } } } ``` 上述代码中,`zipFolder`方法接收两个参数:源文件夹的路径和目标zip文件的路径。该方法首先打开一个ZipOutputStream,然后使用`addFolderToZip`方法从源文件夹中递归添加所有文件和子文件夹。 使用该工具类,你可以压缩任何文件夹,例如: ```java ZipUtils.zipFolder("/path/to/folder", "/path/to/archive.zip"); ``` 这会压缩`/path/to/folder`下的所有文件和子文件夹,并将它们保存在`/path/to/archive.zip`文件中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值