Folder

To create a folder, we need to have a bucket. We cannot create a folder at the root level. Folders can be nested. To create a folder under the bucket, we need to create an object with its content length metadata as 0 and an empty content so that it can be recognized as a folder:

ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentLength(0);

InputStream emptyContent = new ByteArrayInputStream(new byte[0]);

PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, folderName + "/", emptyContent, metadata);

s3.putObject(putObjectRequest);

In the preceding code, you can see that the content length is set to 0, and an empty byte array input has been added. Apart from this, we provided the suffix "/" to the folder name ...

Get Amazon S3 Essentials now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.