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/MakingRequests.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
import java.util.List;
6
7
import com.amazonaws.AmazonServiceException;
8
import com.amazonaws.SdkClientException;
9
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
10
import com.amazonaws.services.s3.AmazonS3;
11
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
12
import com.amazonaws.services.s3.model.ListObjectsRequest;
13
import com.amazonaws.services.s3.model.ObjectListing;
14
import com.amazonaws.services.s3.model.S3ObjectSummary;
15
16
public class MakingRequests {
17
18
public static void main(String[] args) throws IOException {
19
String clientRegion = "*** Client region ***";
20
String bucketName = "*** Bucket name ***";
21
22
try {
23
AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
24
.withCredentials(new ProfileCredentialsProvider())
25
.withRegion(clientRegion)
26
.build();
27
28
// Get a list of objects in the bucket, two at a time, and
29
// print the name and size of each object.
30
ListObjectsRequest listRequest = new ListObjectsRequest().withBucketName(bucketName).withMaxKeys(2);
31
ObjectListing objects = s3Client.listObjects(listRequest);
32
while(true) {
33
List<S3ObjectSummary> summaries = objects.getObjectSummaries();
34
for(S3ObjectSummary summary : summaries) {
35
System.out.printf("Object \"%s\" retrieved with size %d\n", summary.getKey(), summary.getSize());
36
}
37
if(objects.isTruncated()) {
38
objects = s3Client.listNextBatchOfObjects(objects);
39
}
40
else {
41
break;
42
}
43
}
44
}
45
catch(AmazonServiceException e) {
46
// The call was transmitted successfully, but Amazon S3 couldn't process
47
// it, so it returned an error response.
48
e.printStackTrace();
49
}
50
catch(SdkClientException e) {
51
// Amazon S3 couldn't be contacted for a response, or the client
52
// couldn't parse the response from Amazon S3.
53
e.printStackTrace();
54
}
55
}
56
}
57