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