Search code examples
javaamazon-web-servicesamazon-s3aws-sdkaws-java-sdk

How to set next continuation token on AWS ListObjectsV2Request object


I am using AWS SDK for Java 2.15.66. I am trying to list all the objects under a particular folder. I am following code sample here https://docs.aws.amazon.com/AmazonS3/latest/userguide/ListingKeysUsingAPIs.html and had to modify since the classes in the sample are not available in my version of SDK. Following is the code I have to list objects

ListObjectsV2Request req = ListObjectsV2Request.builder()
            .bucket(S3_BUCKET_NAME)
            .prefix(pathBuilder.toString())
            .maxKeys(2)
            .build();
    ListObjectsV2Response result;
    do {
        result = s3Client.listObjectsV2(req);
        for (S3Object s3Object : result.contents()) {
            System.out.printf(" - %s (size: %d)\n", s3Object.key(), s3Object.size());
        }
        req.toBuilder().continuationToken(result.nextContinuationToken());
    } while (result.isTruncated());

This code always prints out the same two objects in each while loop. That is the nextContinuationToken() is never set. I am not able to find any other way to set the continuation token. Help appreciated.


Solution

  • Try with below code, reference link from official aws documentation

    ListObjectsV2Request listObjectsReqManual = ListObjectsV2Request.builder()
                .bucket(bucketName)
                .maxKeys(1)
                .build();
    
        boolean done = false;
        while (!done) {
            ListObjectsV2Response listObjResponse = s3.listObjectsV2(listObjectsReqManual);
            for (S3Object content : listObjResponse.contents()) {
                System.out.println(content.key());
            }
    
            if (listObjResponse.nextContinuationToken() == null) {
                done = true;
            }
    
            listObjectsReqManual = listObjectsReqManual.toBuilder()
                    .continuationToken(listObjResponse.nextContinuationToken())
                    .build();
        }
    

    You need to assign the result of .toBuilder().continuationToken(…) method to a variable