Java操作ZIp文件

这篇博客详细介绍了如何使用Java进行文件打包下载和上传。在下载部分,通过设置HttpServletResponse实现文件的Zip格式下载,同时处理了文件名编码问题。在上传部分,将多个文件打包成Zip后,利用ECS服务上传到指定存储桶,并返回下载链接。注意,ZipOutputStream在上传时需要调用finish()方法以确保文件完整。
摘要由CSDN通过智能技术生成

Java操作文件打包下载

    public void downloadEcsZip(String fileName,List<Map<String,String>> filesMap,HttpServletResponse response) throws AppException {

        // 设置浏览器显示的内容类型为Zip
        response.setContentType("application/zip");
        // 设置文件名
        try {
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName,"UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new AppException("不支持的编码格式");
        }
        try(ZipOutputStream zos = new ZipOutputStream(response.getOutputStream())) {
            // 读取文件的缓存
            EcsHelper ecsHelper = EcsHelper.getInstance();
            for (Map<String,String> file : filesMap) {
                String ecsId = file.get("ecsId");
                String name = file.get("name");
                InputStream inputStream = ecsHelper.readObject(ecsId);
                // 把inputstream写入到zip流里
                writeToZipFile(zos, inputStream, name);
            }
        }catch (Exception e){
            LogHelper.error("下载文件异常!", e);
            throw new AppException("下载文件异常!", e);
        }
    }
    
    private void writeToZipFile(ZipOutputStream zipOutput, InputStream inputStream, String fileName)
            throws IOException {
        try (BufferedInputStream bis = new BufferedInputStream(inputStream)) {
            ZipEntry entry = new ZipEntry(fileName);
            zipOutput.putNextEntry(entry);
            // 向压缩文件中输出数据
            int length;
            byte[] buffer = new byte[4096];
            while ((length = bis.read(buffer)) != -1) {
                zipOutput.write(buffer, 0, length);
            }
        } catch (IOException e) {
            LogHelper.error("将文件写入压缩文件中出现异常:", e);
        } finally {
            if (zipOutput != null) {
                zipOutput.flush();
                zipOutput.closeEntry();
            }
        }
    }

Java操作文件打包上传

    public String packageFile(String fileName, List<Map<String, String>> filesMap,String email) throws AppException {
      String encodeName;
      byte[] srcs;
      // 设置文件名
      try {
          encodeName = URLEncoder.encode(fileName, "UTF-8");
      } catch (UnsupportedEncodingException e) {
          throw new AppException("不支持的编码格式");
      }

      try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
           ZipOutputStream zos = new ZipOutputStream(bos)) {
          // 读取文件的缓存
          EcsHelper ecsHelper = EcsHelper.getInstance();
          for (Map<String, String> file : filesMap) {
              String ecsId = file.get("ecsId");
              String name = file.get("name");
              InputStream inputStream = ecsHelper.readObject(ecsId);
              // 把inputstream写入到zip流里
              writeToZipFile(zos, inputStream, name);
              log.info("打包单个文件进zip完成,zipName="+fileName+",name="+name+",ecsId="+ecsId);
          }
          zos.finish();
          srcs = bos.toByteArray();
          log.info("打包文件进zip完成,zipName="+fileName);
      } catch (Exception e) {
          LogHelper.error("下载Ecs文件异常!", e);
          throw new AppException("下载Ecs文件异常!", e);
      }

      String url= "";
      try (InputStream stream = new ByteArrayInputStream(srcs)) {
          S3ObjectMetadata metadata = new S3ObjectMetadata();
          metadata.setContentDisposition("attachment; filename=" + encodeName);
          String packageBucketName = AppConfig.getInstance().getPackageBucketName();
          String key = CommonUtils.getUUID("N");
          EcsHelper.getInstance().createObject(key, stream, packageBucketName,"application/zip", metadata);
          log.info("上传zip到ecs完成,zipName="+fileName);
          url = EcsHelper.getInstance().getStaticUrl(key, packageBucketName);
          log.info("获取zip链接完成,zipName="+fileName);
      }catch (Exception e){
          LogHelper.error("上传Zip文件异常!", e);
          throw new AppException("上传文件异常!", e);
      }

      return url;
  }

  private void writeToZipFile(ZipOutputStream zipOutput, InputStream inputStream, String fileName)
          throws IOException {
      try (BufferedInputStream bis = new BufferedInputStream(inputStream)) {
          ZipEntry entry = new ZipEntry(fileName);
          zipOutput.putNextEntry(entry);
          // 向压缩文件中输出数据
          int length;
          byte[] buffer = new byte[1024];
          while ((length = bis.read(buffer)) != -1) {
              zipOutput.write(buffer, 0, length);
          }
      } catch (IOException e) {
          LogHelper.error("将文件写入压缩文件中出现异常:", e);
      } finally {
          if (zipOutput != null) {
              zipOutput.flush();
              zipOutput.closeEntry();
          }
      }
  }

注意事项

上传时ZipOutputStream 要手动finish();否则会导致压缩包解压出现末尾损坏的警告。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值