Java导出压缩文件

 

 在很多场景需要导出很多的文件,将其压缩成zip是一个很不错的选择。

先将要压缩的文件路径和名称得到,然后用工具类将其压缩。代码逻辑清晰,使用得修改一些文件路径。
实现类中导出方法中:

String zipFileName = "工单附件" + "-" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".zip";
                        String fileZip = System.getProperty("user.dir") + "/zipTemp/" + zipFileName;
                        File pocZipFile = new File(fileZip);
                        CompressUtil.compress(filePathList, fileZip, false,workOrder.getWorkOrderNo());
                        CompressUtil.downloadZip(response, zipFileName, pocZipFile);
                        boolean b = FileUtils.deleteFileOrDirectory(System.getProperty("user.dir") + "/zipTemp");
                        log.info(b?"删除成功":"删除失败");

 导出的工具类,具体按实际场景改变,仅供参考;


public class CompressUtil {

    /**
     * 生成zip压缩文件
     * @param filePaths
     * @param zipFilePath
     * @param keepDirStructure
     */
    public static void compress(List<Map<String, String>> filePaths, String zipFilePath, Boolean keepDirStructure,String workNo) {
        byte[] buf = new byte[1024 * 8];
        File zipFile = new File(zipFilePath);
        FileUtils.createParentPath(zipFile);
        try {
            if(!zipFile.exists()){
                zipFile.createNewFile();
            }
            ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));
            for (int i = 0; i < filePaths.size(); i++) {
                String relativePath = filePaths.get(i).get("filePath");
                String relativeName = filePaths.get(i).get("fileName");
                if (StringUtils.isEmpty(relativePath)) {
                    continue;
                }
                File sourceFile = new File(relativePath);
                if (sourceFile == null || !sourceFile.exists()) {
                    continue;
                }
                FileInputStream fis = new FileInputStream(sourceFile);
                BufferedInputStream bis = new BufferedInputStream(fis);
                String fileName = "工单附件" + "-" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
                if (keepDirStructure != null && keepDirStructure) {
                    zos.putNextEntry(new ZipEntry(fileName+"/"+workNo +"/"+ relativePath));
                    //zos.putNextEntry(new ZipEntry(relativePath));
                } else {
                    zos.putNextEntry(new ZipEntry(fileName+"/"+workNo + "/" + relativeName));
                }
                int len;
                while ((len = bis.read(buf)) > 0) {
                    zos.write(buf, 0, len);
                }
                zos.closeEntry();
                fis.close();
                bis.close();
                // zos.close();
            }
            zos.close();

            if (!zipFile.exists()) {
                zipFile.createNewFile();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    public static void wordCompress(List<Map<String, String>> filePaths, String zipFilePath, Boolean keepDirStructure) {
        byte[] buf = new byte[1024 * 8];
        File zipFile = new File(zipFilePath);
        FileUtils.createParentPath(zipFile);
        try {
            if(!zipFile.exists()){
                zipFile.createNewFile();
            }
            ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));
            for (int i = 0; i < filePaths.size(); i++) {
                String relativePath = filePaths.get(i).get("filePath");
                String relativeName = filePaths.get(i).get("fileName");
                if (StringUtils.isEmpty(relativePath)) {
                    continue;
                }
                File sourceFile = new File(relativePath);
                if (sourceFile == null || !sourceFile.exists()) {
                    continue;
                }
                FileInputStream fis = new FileInputStream(sourceFile);
                BufferedInputStream bis = new BufferedInputStream(fis);
                String fileName = "工单文档" + "-" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
                if (keepDirStructure != null && keepDirStructure) {
                    zos.putNextEntry(new ZipEntry(fileName+"/"+ relativePath));
                    //zos.putNextEntry(new ZipEntry(relativePath));
                } else {
                    zos.putNextEntry(new ZipEntry(fileName+"/" + relativeName));
                }
                int len;
                while ((len = bis.read(buf)) > 0) {
                    zos.write(buf, 0, len);
                }
                zos.closeEntry();
                fis.close();
                bis.close();
                // zos.close();
            }
            zos.close();

            if (!zipFile.exists()) {
                zipFile.createNewFile();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }





    /**
     * 下载zip
     *
     * @param response
     * @param zipName  浏览器header中zip名称
     * @param zipFile  zipFile文件
     */
    public static void downloadZip(HttpServletResponse response, String zipName, File zipFile) {
        //下载文件
        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/zip");
//            response.setContentType("application/zip");
            response.setHeader("Content-Disposition", "attachment;FileName=" + URLEncoder.encode(zipName, "UTF-8"));
            response.addHeader("Content-Length", "" + zipFile.length());
            ServletOutputStream out = response.getOutputStream();
            int len = 0;
            FileInputStream fis = new FileInputStream(zipFile);
            BufferedInputStream bis = new BufferedInputStream(fis);
            int count = fis.available();
            byte[] buffer = new byte[count];
            while ((len = bis.read(buffer)) > 0) {
                out.write(buffer, 0, len);
                out.flush();
            }
            out.close();
            fis.close();
            bis.close();
            response.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 上面工具类中创建父文档的方法;


 public static void createParentPath(File file) {
        File parentFile = file.getParentFile();
        if (null != parentFile && !parentFile.exists()) {
            parentFile.mkdirs(); // 创建文件夹
            createParentPath(parentFile); // 递归创建父级目录
        }
    }

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值