Home > Blockchain >  How to save/zip binary/octet-stream s3 content to zip
How to save/zip binary/octet-stream s3 content to zip

Time:10-25

I am trying to add s3 bucket files into a zip. The files in the s3 bucket are in binary/octet-stream format.

When I run the below method

 public static void addFileToZip(ZipOutputStream zip, String fileName, InputStream fileContent) throws IOException {
    try {
      zip.putNextEntry(new ZipEntry(fileName));
      IOUtils.copy(fileContent, zip);
      zip.closeEntry();
    } catch (IOException ioe) {
      fileContent.close();
    }
  }
}

The IO Exception below is thrown when executing IOUtils.copy method

"exception": "Premature end of Content-Length delimited message body (expected: 206,034; received: 0)"

Any suggestions on how I can handle this or what am doing wrong? Thank you.

Edit:- @LeeGreiner I am getting the InputStream like this:

public ResponseInputStream<GetObjectResponse> getObject(String key) {
    try (S3Client s3 = s3Client.getClient()) {
      return s3.getObject(
          GetObjectRequest.builder()
              .bucket(bucketName)
              .key(key)
              .build()
      );
    }
  }

CodePudding user response:

You can use a ResponseTransformer to convert the response to an input stream:

s3.getObject(getObjectRequest, ResponseTransformer.toInputStream());

My specific method is as follows (it assumes the s3 connection has already been created):

public static InputStream getObject(String key) throws IOException {

    GetObjectRequest getObjectRequest = GetObjectRequest.builder()
            .bucket(bucketName)
            .key(key)
            .build();

    return s3.getObject(getObjectRequest, ResponseTransformer.toInputStream());
}

The resulting input stream can then be added to your zip file in the usual way.

  • Related