Delete Objects from Amazon S3 Bucket using AWS SDK for Java

In previous post you saw how to Get list of files and folders from specific Amazon S3 directory.
Today I’ll show how to delete a list of objects from S3 bucket.

Please not that AmazonS3Client() is deprecated, so we will use a newest initializer from AWS SDK – AmazonS3ClientBuilder.

AWSCredentials credentials = new BasicAWSCredentials("<AWS accesskey>", "<AWS secretkey>");
AmazonS3 s3client = AmazonS3ClientBuilder.standard()
                    .withCredentials(new AWSStaticCredentialsProvider(credentials))
                    .withRegion(Regions.US_EAST_2)
                    .build();
...

public void deleteObjects(String bucketName, List<String> keys) {

        List<KeyVersion> bulk = new ArrayList<>();
        for (int i = 0; i < keys.size(); i++) {
            bulk.add(new KeyVersion(keys.get(i)));
            if (i % 100 == 0) {
                try {
                    s3Client.deleteObjects(new DeleteObjectsRequest(bucketName).withKeys(bulk));
                } catch (Exception e) {
                    System.err.println(e.getErrorMessage());
                }
                bulk.clear();
            }
        }
        if (bulk.size() > 0) {
            try {
                s3Client.deleteObjects(new DeleteObjectsRequest(bucketName).withKeys(bulk));
            } catch (Exception e) {
                System.err.println(e.getErrorMessage());
            }
        }
    }

Notice that we deleting objects by bulks 100 objects per bulk in sake of performance.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.