Path: blob/master/code_examples/java_examples/S3Examples/ListKeys.java
4084 views
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.1// SPDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-s3-developer-guide/blob/master/LICENSE-SAMPLECODE.)23import java.io.IOException;45import com.amazonaws.AmazonServiceException;6import com.amazonaws.SdkClientException;7import com.amazonaws.auth.profile.ProfileCredentialsProvider;8import com.amazonaws.services.s3.AmazonS3;9import com.amazonaws.services.s3.AmazonS3ClientBuilder;10import com.amazonaws.services.s3.model.ListObjectsV2Request;11import com.amazonaws.services.s3.model.ListObjectsV2Result;12import com.amazonaws.services.s3.model.S3ObjectSummary;1314public class ListKeys {1516public static void main(String[] args) throws IOException {17String clientRegion = "*** Client region ***";18String bucketName = "*** Bucket name ***";1920try {21AmazonS3 s3Client = AmazonS3ClientBuilder.standard()22.withCredentials(new ProfileCredentialsProvider())23.withRegion(clientRegion)24.build();2526System.out.println("Listing objects");2728// maxKeys is set to 2 to demonstrate the use of29// ListObjectsV2Result.getNextContinuationToken()30ListObjectsV2Request req = new ListObjectsV2Request().withBucketName(bucketName).withMaxKeys(2);31ListObjectsV2Result result;3233do {34result = s3Client.listObjectsV2(req);3536for (S3ObjectSummary objectSummary : result.getObjectSummaries()) {37System.out.printf(" - %s (size: %d)\n", objectSummary.getKey(), objectSummary.getSize());38}39// If there are more than maxKeys keys in the bucket, get a continuation token40// and list the next objects.41String token = result.getNextContinuationToken();42System.out.println("Next Continuation Token: " + token);43req.setContinuationToken(token);44} while (result.isTruncated());45}46catch(AmazonServiceException e) {47// The call was transmitted successfully, but Amazon S3 couldn't process48// it, so it returned an error response.49e.printStackTrace();50}51catch(SdkClientException e) {52// Amazon S3 couldn't be contacted for a response, or the client53// couldn't parse the response from Amazon S3.54e.printStackTrace();55}56}57}5859