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/DeleteMultipleObjectsNonVersionedBucket.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.ArrayList;
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.DeleteObjectsRequest;
13
import com.amazonaws.services.s3.model.DeleteObjectsRequest.KeyVersion;
14
import com.amazonaws.services.s3.model.DeleteObjectsResult;
15
16
public class DeleteMultipleObjectsNonVersionedBucket {
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
// Upload three sample objects.
29
ArrayList<KeyVersion> keys = new ArrayList<KeyVersion>();
30
for (int i = 0; i < 3; i++) {
31
String keyName = "delete object example " + i;
32
s3Client.putObject(bucketName, keyName, "Object number " + i + " to be deleted.");
33
keys.add(new KeyVersion(keyName));
34
}
35
System.out.println(keys.size() + " objects successfully created.");
36
37
// Delete the sample objects.
38
DeleteObjectsRequest multiObjectDeleteRequest = new DeleteObjectsRequest(bucketName)
39
.withKeys(keys)
40
.withQuiet(false);
41
42
// Verify that the objects were deleted successfully.
43
DeleteObjectsResult delObjRes = s3Client.deleteObjects(multiObjectDeleteRequest);
44
int successfulDeletes = delObjRes.getDeletedObjects().size();
45
System.out.println(successfulDeletes + " objects successfully deleted.");
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