How to create bucket in S3 using Java – AWS S3 Create Bucket

3 weeks ago Lalit Bhagtani 0

In this tutorial, we will learn about how to create a bucket in S3 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();

Bucket

Every object stored in Amazon S3 is contained within a bucket. Inside a bucket, any name can be used for objects. However, bucket names must be unique across all of Amazon S3. Only a single user can own a bucket in Amazon S3. Ownership of the bucket is retained as long as the owner has an Amazon S3 account.

The bucket names should follow the following rules :- 

  1. Bucket names should not contain underscores
  2. Bucket names should be between 3 and 63 characters long
  3. Bucket names should not end with a dash
  4. Bucket names cannot contain adjacent periods
  5. Bucket names cannot contain dashes next to periods (e.g., “my-.bucket.com” and “my.-bucket” are invalid)
  6. Bucket names cannot contain uppercase characters

Create Bucket

Steps to create and send CreateBucketRequest to S3 are as follows:-

  1. Check if bucket with a given name is already present in the S3 or not, for this invoke a doesBucketExistV2 method on AmazonS3 object by passing bucket name as an argument.
  2. If bucket with the same name does not exist, then Instantiate CreateBucketRequest object by passing a bucket name as an argument, this object will send the client request to S3.
  3. Set canned access control list as PublicRead, this provides full control to bucket owner and read access to all users.
  4. Invoke the createBucket method on AmazonS3 object by passing CreateBucketRequest object as an argument.

Example

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.Bucket;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.CreateBucketRequest;

public class CreateBucket {
	
	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 {			
			
			/* Check if Bucket with given name is present or not */
			if(!s3.doesBucketExistV2("lb-aws-learning")) {
				
				/* Create an Object of CreateBucketRequest */
				CreateBucketRequest request = new CreateBucketRequest("lb-aws-learning");
				
				/* Set Canned ACL as PublicRead */
				request.setCannedAcl(CannedAccessControlList.PublicRead);
				
				/* Send Create Bucket Request */
				Bucket result = s3.createBucket(request);
				
	            System.out.println("Bucket Name : " + result.getName());
	            
	            System.out.println("Creation Date : " + result.getCreationDate());
				
			} else {
				
				System.out.println("Bucket with given name is already present");
				
			}
        } catch (AmazonServiceException e) {
        	
            System.out.println(e.getErrorMessage());
            
        } finally {
        	
        	if(s3 != null) {
        		s3.shutdown();
        	}        	
        }		
	}
}

References :-

  1. CreateBucketRequest Java Docs
  2. Bucket Java Docs

That’s all for how to create a bucket in S3 using java language. If you liked it, please share your thoughts in comments section and share it with others too.