In this Java Amazon S3 tutorial, I’d like to share some code examples for programmatically creating folders in a bucket on Amazon S3 server, using AWS SDK for Java.
To follow this guide, you must have an AWS SDK for S3 set up for your Java Maven project. If not, kindly follow this article.
programming/
programming/java/ programming/python/Though you can see folders on AWS Management console as shown below, they are actually objects with type “folder” - not folders like in hierarchical file system:You can also browse these folders in way that is very much like folders on your computer, but they are all actually flat objects in S3.package net.codejava.aws; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.PutObjectRequest; public class CreateFolderExample { public static void main(String[] args) { String bucketName = "code-java-bucket"; String folderName = "projects/docs/"; S3Client client = S3Client.builder().build(); PutObjectRequest request = PutObjectRequest.builder() .bucket(bucketName).key(folderName).build(); client.putObject(request, RequestBody.empty()); System.out.println("Folder " + folderName + " is ready."); } }You see, the code is self-explanatory. It sends a PutObjectRequest to S3 server for creating an empty object. You can specify any hierarchy-like folder name, as it’s actually object key.
package net.codejava.aws; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.core.waiters.WaiterResponse; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.HeadObjectRequest; import software.amazon.awssdk.services.s3.model.HeadObjectResponse; import software.amazon.awssdk.services.s3.model.PutObjectRequest; import software.amazon.awssdk.services.s3.waiters.S3Waiter; public class CreateFolderExample { public static void main(String[] args) { String bucketName = "nam-public-images"; String folderName = "asia/vietnam/"; S3Client client = S3Client.builder().build(); PutObjectRequest request = PutObjectRequest.builder() .bucket(bucketName).key(folderName).build(); client.putObject(request, RequestBody.empty()); S3Waiter waiter = client.waiter(); HeadObjectRequest requestWait = HeadObjectRequest.builder() .bucket(bucketName).key(folderName).build(); WaiterResponse<HeadObjectResponse> waiterResponse = waiter.waitUntilObjectExists(requestWait); waiterResponse.matched().response().ifPresent(System.out::println); System.out.println("Folder " + folderName + " is ready."); } }This code will wait until the folder exists, so you can perform your custom logics afterward.That’s a couple of examples about creating folders on Amazon S3. To see the coding in action, kindly watch my video on YouTube: