Get an S3Object from a GetObjectResponse in AWS Java SDK 2.0
Asked Answered
C

2

15

In AWS Java SDK 1.x, I could get an S3Object from an S3Client like this.

S3Object obj = mS3Client.getObject(pBucket, pKey);

I'm trying to replicate that functionality using AWS Java SDK 2.0 (and end up with an S3Object), but the closest I can get is a GetObjectResponse, and I can't find any simple method calls to turn the response into an S3Object.

GetObjectResponse response = mS3Client.getObject(
        GetObjectRequest.builder()
                .bucket(pBucket)
                .key(pKey)
                .build())
        .response();

How can I get an S3Object from the 2.0 S3Client, or build one from the GetObjectResponse?

Coracoid answered 30/1, 2019 at 18:33 Comment(0)
M
8

use ResponseInputStream. Hope the below code solves your problem.

GetObjectRequest request = GetObjectRequest.builder()
    .bucket("BucketName")
    .key("key")
    .build();
ResponseInputStream<GetObjectResponse> s3objectResponse = s3Client
    .getObject(request);
BufferedReader reader = new BufferedReader(new InputStreamReader(s3objectResponse));

String line;            
while ((line = reader.readLine()) != null) {            
    System.out.println(line);
}
Machuca answered 3/6, 2019 at 7:23 Comment(2)
For many different ways of converting from InputStream to String, see https://mcmap.net/q/36074/-how-do-i-read-convert-an-inputstream-into-a-string-in-java/150884Hypethral
This is helpful, but doesn't show how to get an instance of S3Object like the question is asking.Modestamodeste
M
0

Same issue here, but I had to return byte array of content.

public byte[] getContent(String bucketName, String keyInBucket) {
    // Get Client
    S3Client s3client = getS3Client();
    // Get S3 Object
    GetObjectRequest getObjectRequest = GetObjectRequest.builder()
        .bucket(bucketName)
        .key(keyInBucket)
        .build();
    // As Byte array 
    ResponseBytes<GetObjectResponse> response = s3client.getObject(getObjectRequest, ResponseTransformer.toBytes());
    return response.asByteArray();
}
Myosin answered 7/4, 2022 at 14:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.