- AWS Code Sample demonstrates how to list object versions in a version-enabled S3 bucket.

/** * Copyright 2018-2019, Inc. or its affiliates. All Rights Reserved. * * This file is licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. A copy of * the License is located at * * * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ import com.amazonaws.AmazonServiceException; import com.amazonaws.SdkClientException; import com.amazonaws.auth.profile.ProfileCredentialsProvider; import com.amazonaws.regions.Regions; import; import; import; import; import; public class ListKeysVersioningEnabledBucket { public static void main(String[] args) { Regions clientRegion = Regions.DEFAULT_REGION; String bucketName = "*** Bucket name ***"; try { AmazonS3 s3Client = AmazonS3ClientBuilder.standard() .withCredentials(new ProfileCredentialsProvider()) .withRegion(clientRegion) .build(); // Retrieve the list of versions. If the bucket contains more versions // than the specified maximum number of results, Amazon S3 returns // one page of results per request. ListVersionsRequest request = new ListVersionsRequest() .withBucketName(bucketName) .withMaxResults(2); VersionListing versionListing = s3Client.listVersions(request); int numVersions = 0, numPages = 0; while (true) { numPages++; for (S3VersionSummary objectSummary : versionListing.getVersionSummaries()) { System.out.printf("Retrieved object %s, version %s\n", objectSummary.getKey(), objectSummary.getVersionId()); numVersions++; } // Check whether there are more pages of versions to retrieve. If // there are, retrieve them. Otherwise, exit the loop. if (versionListing.isTruncated()) { versionListing = s3Client.listNextBatchOfVersions(versionListing); } else { break; } } System.out.println(numVersions + " object versions retrieved in " + numPages + " pages"); } 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(); } } }

Sample Details

Service: s3

Last tested: 2019-01-28

Author: AWS

Type: full-example