Inderjeet Chawla
Inderjeet Chawla

Reputation: 39

How to delete multiple objects in an Amazon S3 bucket using Java V2

So I want to delete all the objects that could be inside a folder in s3 (basically with a certain prefix).
How do I do that? I am currently using this while (true) loop, but I am told it is not a good approach to use while (true).
This is what I am using right now.

while (true) {
    for (S3ObjectSummary objectSummary: objectListing.getObjectSummaries()) {
        this.s3Client.deleteObject(bucketName, objectSummary.getKey());
    }

    if (objectListing.isTruncated()) {
        objectListing = s3Client.listNextBatchOfObjects(objectListing);
    } else {
        break;
    }
}

Upvotes: 3

Views: 5486

Answers (1)

smac2020
smac2020

Reputation: 10704

When using the AWS SDK for Java V2 S3 Client, you can set up your code to use a List of ObjectIdentifier objects to delete. Add a new entry to the List for each object to delete. Specify the path where the object is located in the ObjectIdentifier key value. This is where you specify the path in a bucket where the object is located.

You need to populate the LIST with the number of objects that you want to delete. So if you have 20 objects - then you need to add 20 entries to the List each with a valid key value that references the object to delete.

Then call deleteObjects(). This is a cleaner way to delete many objects. That is, you can delete multiple objects in 1 call vs many calls.

See this code.

 public static void deleteBucketObjects(S3Client s3, String bucketName, String objectName) {

        ArrayList<ObjectIdentifier> toDelete = new ArrayList<>();
        toDelete.add(ObjectIdentifier.builder()
            .key(objectName)
            .build());

        try {
            DeleteObjectsRequest dor = DeleteObjectsRequest.builder()
                .bucket(bucketName)
                .delete(Delete.builder()
                .objects(toDelete).build())
                .build();
            
            s3.deleteObjects(dor);

        } catch (S3Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        
        System.out.println("Done!");
    }

Upvotes: 3

Related Questions