Java操作ZIp文件

目录

  • Java操作文件打包下载
  • Java操作文件打包上传
  • 注意事项

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();否则会导致压缩包解压出现末尾损坏的警告。

你可能感兴趣的:(Java,java)