[Java] Delete AWS S3 objects in Java

less than 1 minute read

You can use the AWS SDK for Java to delete S3 objects.

Delete one object

You can delete the specified object by specifying the bucket name and object key.

try {
    final AmazonS3 s3 = new AmazonS3Client();
    s3.deleteObject(bucket_name, object_key);
} catch (AmazonServiceException e) {
    e.printStackTrace();
}

Delete all objects in specified folder

If you specify the bucket name and folder name, you can delete all the objects in the specified folder.

try {
    final AmazonS3 s3 = new AmazonS3Client();
ObjectListing objListing = s3.listObjects(bucket_name,folder_nm);
    List<S3ObjectSummary> objList = objListing.getObjectSummaries();
    for (S3ObjectSummary obj :objList) {
         s3.deleteObject(bucket_name, obj.getKey());
    }
} catch (AmazonServiceException e) {
    e.printStackTrace();
}

s3.listObjects requires the following policy settings.

PolicyDocument:
      Version: 2012-10-17
      Statement:
        -Effect: Allow
          Action: "s3:*"
          Resource:
            -"arn:aws:s3:::bucket-test-01"
            -"arn:aws:s3:::bucket-test-01/*"