Home > front end >  How to empty Amazon S3 Bucket using AWS Java SDK?
How to empty Amazon S3 Bucket using AWS Java SDK?

Time:10-31

I was unable to find any documentation on how to empty an Amazon S3 bucket programmatically in Java. Any help will be appreciated.

CodePudding user response:

To delete Amazon S3 objects using Java, you can use the AWS SDK for Java V2. To empty a bucket, first get a list of all objects in the Bucket using this code:

public static void listBucketObjects(S3Client s3, String bucketName ) {

       try {
            ListObjectsRequest listObjects = ListObjectsRequest
                    .builder()
                    .bucket(bucketName)
                    .build();

            ListObjectsResponse res = s3.listObjects(listObjects);
            List<S3Object> objects = res.contents();

            for (ListIterator iterVals = objects.listIterator(); iterVals.hasNext(); ) {
                S3Object myValue = (S3Object) iterVals.next();
                System.out.print("\n The name of the key is "   myValue.key());
                System.out.print("\n The object is "   calKb(myValue.size())   " KBs");
                System.out.print("\n The owner is "   myValue.owner());

             }

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

For each object, you can delete it using this code:

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

    ArrayList<ObjectIdentifier> toDelete = new ArrayList<ObjectIdentifier>();
    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!");
}

You can find these examples and many others in AWS Github here:

Amazon S3 Java code examples

  • Related