Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete a folder and its content AWS S3 java

Is it possible to delete a folder(In S3 bucket) and all its content with a single api request using java sdk for aws. For browser console we can delete and folder and its content with a single click and I hope that same behavior should be available using the APIs also.

like image 905
Munish Dhiman Avatar asked Feb 24 '17 15:02

Munish Dhiman


People also ask

How do I delete a folder from my AWS S3?

In the Buckets list, choose the name of the bucket that you want to delete folders from. In the Objects list, select the check box next to the folders and objects that you want to delete. Choose Delete.

How do I delete items from my AWS S3?

To delete the object, select the object, and choose delete and confirm your choice by typing delete in the text field. On, Amazon S3 will permanently delete the object version. Select the object version that you want to delete, and choose delete and confirm your choice by typing permanently delete in the text field.

Does S3 lifecycle delete folders?

The subfolders DO get deleted when the retention policy set to: "This rule applies to all objects in the bucket". Hopefully, an option will be added soon to AWS retention policy so that it can be set to no include Folders. Hope this helps !


2 Answers

There is no such thing as folders in S3; There are simply files with slashes in the filenames.

Browser console will visualize these slashes as folders, but they're not real.

You can delete all files with the same prefix, but first you need to look them up with list_objects(), then you can batch delete them.

For code snippet using Java sdk please refer below doc

http://docs.aws.amazon.com/AmazonS3/latest/dev/DeletingMultipleObjectsUsingJava.html

like image 71
Amit Avatar answered Sep 17 '22 14:09

Amit


You can specify keyPrefix in ListObjectsRequest.

For example, consider a bucket that contains the following keys:

  • foo/bar/baz
  • foo/bar/bash
  • foo/bar/bang
  • foo/boo

And you want to delete files from foo/bar/baz.

if (s3Client.doesBucketExist(bucketName)) {
        ListObjectsRequest listObjectsRequest = new ListObjectsRequest()
                .withBucketName(bucketName)
                .withPrefix("foo/bar/baz");

        ObjectListing objectListing = s3Client.listObjects(listObjectsRequest);

        while (true) {
            for (S3ObjectSummary objectSummary : objectListing.getObjectSummaries()) {
                s3Client.deleteObject(bucketName, objectSummary.getKey());
            }
            if (objectListing.isTruncated()) {
                objectListing = s3Client.listNextBatchOfObjects(objectListing);
            } else {
                break;
            }
        }
    }

https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/s3/model/ListObjectsRequest.html

like image 45
Nikolas Avatar answered Sep 16 '22 14:09

Nikolas