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?

2 Answers 2

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);
}
2
  • 3
    For many different ways of converting from InputStream to String, see stackoverflow.com/q/309424/150884 Commented May 28, 2021 at 12:05
  • 1
    This is helpful, but doesn't show how to get an instance of S3Object like the question is asking.
    – Jake
    Commented Jul 14, 2023 at 12:28
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();
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.