How to delete object from S3 bucket using Java – AWS S3 Delete Object

2 weeks ago Lalit Bhagtani 0

AWS S3 Delete Object – In this tutorial, we will learn about how to delete an object from Amazon S3 bucket using java language.

Project Setup

Create a simple maven project in your favorite IDE and add below mentioned dependency in your pom.xml file.

<dependency>
  <groupId>com.amazonaws</groupId>
  <artifactId>aws-java-sdk-s3</artifactId>
  <version>1.11.533</version>
</dependency>

For latest version of aws library, check this page.

S3 Connection

Create an object of AmazonS3 ( com.amazonaws.services.s3.AmazonS3 ) class for sending a client request to S3. To get instance of this class, we will use AmazonS3ClientBuilder builder class. It requires three important parameters :- 

  1. Region :- It is a region where S3 table will be stored.
  2. ACCESS_KEY :- It is a access key for using S3. You can generate this key, using aws management console.
  3. SECRET_KEY :- It is a secret key of above mentioned access key.

Here is a code example :-

AmazonS3 s3 = AmazonS3ClientBuilder.standard()
				.withRegion(Regions.AP_SOUTH_1)
				.withCredentials(new AWSStaticCredentialsProvider
                                                    (new BasicAWSCredentials("ACCESS_KEY","SECRET_KEY")))
				.build();

Delete Object

An AmazonS3 client provides two different methods for deleting an Object from an S3 bucket. One can delete a single Object and another one can delete multiple Objects from S3 bucket.

AmazonS3.deleteObject method deletes a single object from the S3 bucket. A bucket name and Object Key are only information required for deleting the object. For example, if deleteObject(“bucket-1”, “s3.png”) method is invoked, then the s3.png Object will get deleted from bucket-1.

AmazonS3.deleteObjects method deletes one or more objects from the S3 bucket.

Example

import java.util.Arrays;

import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.DeleteObjectsRequest;
import com.amazonaws.services.s3.model.DeleteObjectsRequest.KeyVersion;
import com.amazonaws.services.s3.model.DeleteObjectsResult;

public class DeleteObjects {

	public static void main(String[] args) {
		
		/* Create S3 Client Object */
		AmazonS3 s3 = AmazonS3ClientBuilder
				.standard()
				.withRegion(Regions.AP_SOUTH_1)
				.withCredentials(new AWSStaticCredentialsProvider(
                                    new BasicAWSCredentials("ACCESS_KEY","SECRET_KEY")))
				.build();
		
		try {	
			
			/* Send Delete Object Request */
			/* Delete single object 's3.png' */
			s3.deleteObject("lb-aws-learning", "s3.png");
			
			/* Create an Object of DeleteObjectsRequest - Arguments: BucketName */
			DeleteObjectsRequest request = new DeleteObjectsRequest("lb-aws-learning");
			
			/* Set Object Keys to delete */ 
			request.setKeys(Arrays.asList(new KeyVersion[] { new KeyVersion("a.png"), new KeyVersion("b.png") }));
			
			/* Send Delete Objects Request */
			DeleteObjectsResult result = s3.deleteObjects(request);
			
			/* Printing Deleted Object Keys */
			if (result.getDeletedObjects() != null) {
				result.getDeletedObjects().stream().forEach(e -> System.out.println(e.getKey()));
			}
            
        } catch (AmazonServiceException e) {
        	
            System.out.println(e.getErrorMessage());
            
        } finally {
        	
        	if(s3 != null) {
        		s3.shutdown();
        	}        	
        }
	}
}

References :-

  1. DeleteObjectRequest Java Docs

That’s all for how to delete an object from Amazon S3 bucket using java language (AWS S3 Delete Object). If you liked it, please share your thoughts in comments section and share it with others too.