How to delete files recursively from an S3 bucket

后端 未结 12 470
不知归路
不知归路 2021-01-29 23:54

I have the following folder structure in S3. Is there a way to recursively remove all files under a certain folder (say foo/bar1 or foo or foo/bar2/1 ..)

         


        
12条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-30 00:31

    In case if you want to remove all objects with "foo/" prefix using Java AWS SDK 2.0

    import java.util.ArrayList;
    import java.util.Iterator;
    import software.amazon.awssdk.services.s3.S3Client;
    import software.amazon.awssdk.services.s3.model.*;
    
    //...
    
    ListObjectsRequest listObjectsRequest = ListObjectsRequest.builder()
        .bucket(bucketName)
        .prefix("foo/")
        .build()
    ;
    ListObjectsResponse objectsResponse = s3Client.listObjects(listObjectsRequest);
    
    while (true) {
        ArrayList objects = new ArrayList<>();
    
        for (Iterator iterator = objectsResponse.contents().iterator(); iterator.hasNext(); ) {
            S3Object s3Object = (S3Object)iterator.next();
            objects.add(
                ObjectIdentifier.builder()
                    .key(s3Object.key())
                    .build()
            );
        }
    
        s3Client.deleteObjects(
            DeleteObjectsRequest.builder()
                .bucket(bucketName)
                .delete(
                    Delete.builder()
                        .objects(objects)
                        .build()
                )
                .build()
        );
    
        if (objectsResponse.isTruncated()) {
            objectsResponse = s3Client.listObjects(listObjectsRequest);
            continue;
        }
    
        break;
    };
    

提交回复
热议问题