Amazon Simple Storage Service
Developer Guide (API Version 2006-03-01)

Listing Keys Using the AWS SDK for Java

The following example lists the object keys in a bucket. The example uses pagination to retrieve a set of object keys. If there are more keys to return after the first page, Amazon S3 includes a continuation token in the response. The example uses the continuation token in the subsequent request to fetch the next set of object keys.

For instructions on creating and testing a working sample, see Testing the Amazon S3 Java Code Examples.

import; import com.amazonaws.AmazonServiceException; import com.amazonaws.SdkClientException; import com.amazonaws.auth.profile.ProfileCredentialsProvider; import; import; import; import; import; public class ListKeys { public static void main(String[] args) throws IOException { String clientRegion = "*** Client region ***"; String bucketName = "*** Bucket name ***"; try { AmazonS3 s3Client = AmazonS3ClientBuilder.standard() .withCredentials(new ProfileCredentialsProvider()) .withRegion(clientRegion) .build(); System.out.println("Listing objects"); // maxKeys is set to 2 to demonstrate the use of // ListObjectsV2Result.getNextContinuationToken() ListObjectsV2Request req = new ListObjectsV2Request().withBucketName(bucketName).withMaxKeys(2); ListObjectsV2Result result; do { result = s3Client.listObjectsV2(req); for (S3ObjectSummary objectSummary : result.getObjectSummaries()) { System.out.printf(" - %s (size: %d)\n", objectSummary.getKey(), objectSummary.getSize()); } // If there are more than maxKeys keys in the bucket, get a continuation token // and list the next objects. String token = result.getNextContinuationToken(); System.out.println("Next Continuation Token: " + token); req.setContinuationToken(token); } while (result.isTruncated()); } catch(AmazonServiceException e) { // The call was transmitted successfully, but Amazon S3 couldn't process // it, so it returned an error response. e.printStackTrace(); } catch(SdkClientException e) { // Amazon S3 couldn't be contacted for a response, or the client // couldn't parse the response from Amazon S3. e.printStackTrace(); } } }