欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

MultipartFile 类型文件批量压缩到一个zip

程序员文章站 2022-07-11 14:31:09
标题 MultipartFile类型文件批量压缩到一个zipprivate String mkZip(MultipartFile[] targetFiles) throws IOException { List files=new ArrayList<>(); for (MultipartFile m:targetFiles) { String dateString = DateUtil.getDateStrin...

MultipartFile 类型文件批量压缩到一个zip

private String mkZip(MultipartFile[] targetFiles) throws IOException {
        List<File> files=new ArrayList<>();
        for (MultipartFile m:targetFiles) {
            String dateString = DateUtil.getDateString(new Date(), DateUtil.DATE_TIME_PATTERN);
            File file = new File("C:/temp", dateString + m.getOriginalFilename());
            file.setWritable(true, false);
            m.transferTo(file);
            files.add(file);
        }
        File zip = new File("C:/temp/"+System.currentTimeMillis() + ".zip");
        zip.setWritable(true, false);
        zip.createNewFile();
        String fileFolders = zipFileFolders(files, zip);
       
        return fileFolders ;
    }
 /**
     * 功能:压缩多个文件,文件夹成一个zip文件
     * @param srcfile:源文件列表
     * @param zipfile:压缩后的文件
     *
     */
    public String zipFileFolders(List<File> srcfile, File zipfile) {
        byte[] buf = new byte[1024];
        ZipOutputStream out = null;
        try {
            //ZipOutputStream类:完成文件或文件夹的压缩
            out = new ZipOutputStream(new FileOutputStream(zipfile));
            for (int i = 0; i < srcfile.size(); i++) {
                FileInputStream in = new FileInputStream(srcfile.get(i));
                String filePath="";
                if (filePath == null)
                    filePath = "";
                else
                    filePath += "/";
                out.putNextEntry(new ZipEntry(filePath + srcfile.get(i).getName()));
                int len;
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                out.closeEntry();
                in.close();
            }
            out.close();
            return zipfile.getAbsolutePath();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

本文地址:https://blog.csdn.net/weixin_45241756/article/details/112007441

相关标签: java zip poi