preload preload


[How-To] Create a folder programmatically in S3 using Amazon AWS Java SDK

This post is going to show you how you can programmatically create the folder in Amazon AWS S3.

As we all know that S3 only understand files & the folder representations which we see in the S3 buckets are mere prefixes for your files. From the AWS console, it is very easy to create the folder & AWS provide option to do it. For a lot of peoples who want to write AWS S3 utilities or clients, it is sometime desirable that they also provide the option to their users to create the folder.

Below are the basic requirement for creation of folder in S3 programmatically. We will then see how to do the same in Amazon provided AWS Java SDK

1. The S3 key should end with forward slash “/”.

2. The content-length should be set to 0.

3. The content should be empty or blank.

The following Java code demonstrates this using the Amazon AWS Java SDK.


import java.io.ByteArrayInputStream;
import java.io.InputStream;

import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;

public class S3Folder {
	private static final String AWS_KEY = "your-aws-key";
	private static final String AWS_SECRET = "your-aws-secret";
	private static final String BUCKET = "s3-bucket-location";
	private final static String FOLDER_SUFFIX = "/";
	final static AmazonS3Client client;

	static {
		// Create S3 Client object using AWS KEY & SECRET
		client = new AmazonS3Client(
				new BasicAWSCredentials(AWS_KEY, AWS_SECRET));
	}

	public void create(String foldername) {
		// TODO validate foldername 

		// Create metadata for your folder & set content-length to 0
		ObjectMetadata metadata = new ObjectMetadata();
		metadata.setContentLength(0);

		// Create empty content
		InputStream emptyContent = new ByteArrayInputStream(new byte[0]);

		// Create a PutObjectRequest passing the foldername suffixed by /
		PutObjectRequest putObjectRequest =
				new PutObjectRequest(BUCKET, foldername + FOLDER_SUFFIX,
						emptyContent, metadata);

		// Send request to S3 to create folder
		client.putObject(putObjectRequest);
	}

	public static void main(String[] args) {
		S3Folder s3Folder = new S3Folder();
		s3Folder.create("myfolder");
	}
}

Pretty neat & easy…huh!!

Liked the content? Then why not share with your pals

  • 2 responses to "[How-To] Create a folder programmatically in S3 using Amazon AWS Java SDK"

  • vishal
    19:25 on April 17th, 2015

    thankss

  • Ashish
    10:33 on April 24th, 2015

    Thanks …. really helped in solving an important issue

  • Leave a Reply

    * Required
    ** Your Email is never shared