AWS S3 Java Example

Here’s an example of how to use the AWS SDK for Java to interact with Amazon Simple Storage Service (S3) to create a new bucket, upload a file, and list the contents of the bucket:

First, you need to include the AWS SDK for Java in your project, you can do this by adding the following dependency to your pom.xml file (if you’re using maven)


Next, create an instance of the AmazonS3Client class, providing your AWS credentials and the region where the bucket will be created:

AmazonS3 s3client = AmazonS3ClientBuilder.standard()
    .withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials("YOUR_ACCESS_KEY", "YOUR_SECRET_KEY")))

Create a new bucket:


Upload a file to the bucket:

s3client.putObject("my-new-bucket", "file.txt", new File("path/to/file.txt"));

List the contents of the bucket:

ObjectListing objectListing = s3client.listObjects("my-new-bucket");
for (S3ObjectSummary objectSummary : objectListing.getObjectSummaries()) {
    System.out.println(" - " + objectSummary.getKey() + "  " +
                       "(size = " + objectSummary.getSize() + ")");

It’s important to note that the above code is a simple example, and in a real-world scenario you may want to handle exceptions, and also consider the security aspect of storing and sharing the credentials.

You should also consider the cost of the storage and data transfer when working with S3, and also consider the performance aspect of your use case before choosing the appropriate storage class.

Please follow and like us:
Content Protection by