Zip文件夹导出工具类

@Slf4j
public class FileZipUtil {

    private static MinioService minioService = SpringUtils.getBean(MinioService.class);
    /**
     * 将指定路径下的所有文件打包zip导出
     * @param response HttpServletResponse
     * @param sourceFilePath 要打包的路径
     * @param fileName 下载时的文件名称
     * @param postfix 下载时的文件后缀 .zip/.rar
     */
    public static void exportZip(HttpServletResponse response, String sourceFilePath, String fileName, String postfix) {
        // 默认文件名以时间戳作为前缀
        if(StringUtils.isBlank(fileName)){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            fileName = sdf.format(new Date());
        }
        String downloadName = fileName + postfix;
        // 将文件进行打包下载
        try {
            OutputStream os = response.getOutputStream();
            // 接收压缩包字节
            byte[] data = createZip(sourceFilePath);
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.addHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Expose-Headers", "*");
            // 下载文件名乱码问题
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(downloadName, "UTF-8"));
            //response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + downloadName);
            response.addHeader("Content-Length", "" + data.length);
            response.setContentType("application/octet-stream;charset=UTF-8");
            IOUtils.write(data, os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            deleteAllFile(new File(sourceFilePath));
        }
    }

    /**
     * 创建zip文件
     * @param sourceFilePath
     * @return byte[]
     * @throws Exception
     */
    private static byte[] createZip(String sourceFilePath) throws Exception{
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        // 将目标文件打包成zip导出
        File file = new File(sourceFilePath);
        handlerFile(zip, file,"");
        // 无异常关闭流,它将无条件的关闭一个可被关闭的对象而不抛出任何异常。
        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();
    }

    /**
     * 打包处理
     * @param zip
     * @param file
     * @param dir
     * @throws Exception
     */
    private static void handlerFile(ZipOutputStream zip, File file, String dir) throws Exception {
        // 如果当前的是文件夹,则循环里面的内容继续处理
        if (file.isDirectory()) {
            //得到文件列表信息
            File[] fileArray = file.listFiles();
            if (fileArray == null) {
                return;
            }
            //将文件夹添加到下一级打包目录
            zip.putNextEntry(new ZipEntry(dir + "/"));
            dir = dir.length() == 0 ? "" : dir + "/";
            // 递归将文件夹中的文件打包
            for (File f : fileArray) {
                handlerFile(zip, f, dir + f.getName());
            }
        } else {
            // 如果当前的是文件,打包处理
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
            ZipEntry entry = new ZipEntry(dir);
            zip.putNextEntry(entry);
            zip.write(FileUtils.readFileToByteArray(file));
            IOUtils.closeQuietly(bis);
            zip.flush();
            zip.closeEntry();
        }
    }


    public static Boolean deleteHtmlFile(File file) {
        //判断文件不为null或文件目录存在
        if (file == null || !file.exists()) {
            System.out.println("文件删除失败,请检查文件是否存在以及文件路径是否正确");
            return false;
        }
        //获取目录下子文件
        File[] files = file.listFiles();
        //遍历该目录下的文件对象
        for (File f : files) {
            //删除html文件
            if (f.getName().toString().endsWith(".html")){
                f.delete();
            }
        }
        return true;
    }


    public static Boolean deleteAllFile(File file) {
        //判断文件不为null或文件目录存在
        if (file == null || !file.exists()) {
            System.out.println("文件删除失败,请检查文件是否存在以及文件路径是否正确");
            return false;
        }
        //获取目录下子文件
        File[] files = file.listFiles();
        //遍历该目录下的文件对象
        for (File f : files) {
            //删除文件
            f.delete();
        }
        file.delete();
        return true;
    }


    public static String get32UUIDPath(String tempFilePath) {
        tempFilePath = !tempFilePath.endsWith("/") ? tempFilePath + "/" : tempFilePath;
        return tempFilePath + UUID.randomUUID().toString().trim().replaceAll("-", "") + "/";
    }

    /**
     * 创建单个文件夹
     *
     * @param filePath 文件夹路径
     * @throws FileExistsException
     * @throws FileNotFoundException
     */
    public static void createFolder(String filePath) throws FileExistsException, FileNotFoundException {
        log.info("============ temp filePath ============", filePath);
        File root = new File(filePath);
        if (root.exists()) {
//            throw new FileExistsException();
        } else {
            if (!root.mkdir()) {
                throw new FileNotFoundException("create file error");
            }
        }
    }



    /**
     * 查询minio中prefixList的图片,并在服务器创建临时文件夹,导出后删除临时文件夹
     *
     * @param bucketName   桶名
     * @param prefixList   前缀集合
     * @param tempFilePath 临时文件路径
     * @throws Exception
     */
    public static void createTempFiles(String bucketName, List<String> prefixList, String tempFilePath) throws Exception {
        createFolder(tempFilePath);

        for (String prefix : prefixList) {
            List<String> objectNames = minioService.listObjectsByPrefix(bucketName, prefix);
            objectNames = objectNames.stream().filter(item -> !item.contains("blob")).collect(Collectors.toList());
            if (!Objects.isNull(objectNames) && !objectNames.isEmpty()) {
                for (String objectName : objectNames) {
                    OutputStream os = new FileOutputStream(tempFilePath +"/" + objectName.substring(objectName.lastIndexOf("/")));
                    InputStream is = minioService.getObject(bucketName, objectName);
                    IOUtils.copy(is, os);
                    os.flush();
                    os.close();
                }
            }
        }
    }


}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值