Path: blob/master/code_examples/java_examples/S3Examples/DeleteMultipleObjectsNonVersionedBucket.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;4import java.util.ArrayList;56import com.amazonaws.AmazonServiceException;7import com.amazonaws.SdkClientException;8import com.amazonaws.auth.profile.ProfileCredentialsProvider;9import com.amazonaws.services.s3.AmazonS3;10import com.amazonaws.services.s3.AmazonS3ClientBuilder;11import com.amazonaws.services.s3.model.DeleteObjectsRequest;12import com.amazonaws.services.s3.model.DeleteObjectsRequest.KeyVersion;13import com.amazonaws.services.s3.model.DeleteObjectsResult;1415public class DeleteMultipleObjectsNonVersionedBucket {1617public static void main(String[] args) throws IOException {18String clientRegion = "*** Client region ***";19String bucketName = "*** Bucket name ***";2021try {22AmazonS3 s3Client = AmazonS3ClientBuilder.standard()23.withCredentials(new ProfileCredentialsProvider())24.withRegion(clientRegion)25.build();2627// Upload three sample objects.28ArrayList<KeyVersion> keys = new ArrayList<KeyVersion>();29for (int i = 0; i < 3; i++) {30String keyName = "delete object example " + i;31s3Client.putObject(bucketName, keyName, "Object number " + i + " to be deleted.");32keys.add(new KeyVersion(keyName));33}34System.out.println(keys.size() + " objects successfully created.");3536// Delete the sample objects.37DeleteObjectsRequest multiObjectDeleteRequest = new DeleteObjectsRequest(bucketName)38.withKeys(keys)39.withQuiet(false);4041// Verify that the objects were deleted successfully.42DeleteObjectsResult delObjRes = s3Client.deleteObjects(multiObjectDeleteRequest);43int successfulDeletes = delObjRes.getDeletedObjects().size();44System.out.println(successfulDeletes + " objects successfully deleted.");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