AWS Code Sample

The AWS Documentation website is getting a new look!
Try it now and let us know what you think. Switch to the new look >>

You can return to the original look by selecting English in the language selector above. demonstrates how to create a new S3 bucket.

/* Copyright 2010-2019, Inc. or its affiliates. All Rights Reserved. This file is licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package aws.example.s3; import com.amazonaws.regions.Regions; import; import; import; import; import java.util.List; /** * Create an Amazon S3 bucket. * * This code expects that you have AWS credentials set up per: * */ public class CreateBucket { public static Bucket getBucket(String bucket_name) { final AmazonS3 s3 = AmazonS3ClientBuilder.standard().withRegion(Regions.DEFAULT_REGION).build(); Bucket named_bucket = null; List<Bucket> buckets = s3.listBuckets(); for (Bucket b : buckets) { if (b.getName().equals(bucket_name)) { named_bucket = b; } } return named_bucket; } public static Bucket createBucket(String bucket_name) { final AmazonS3 s3 = AmazonS3ClientBuilder.standard().withRegion(Regions.DEFAULT_REGION).build(); Bucket b = null; if (s3.doesBucketExistV2(bucket_name)) { System.out.format("Bucket %s already exists.\n", bucket_name); b = getBucket(bucket_name); } else { try { b = s3.createBucket(bucket_name); } catch (AmazonS3Exception e) { System.err.println(e.getErrorMessage()); } } return b; } public static void main(String[] args) { final String USAGE = "\n" + "CreateBucket - create an S3 bucket\n\n" + "Usage: CreateBucket <bucketname>\n\n" + "Where:\n" + " bucketname - the name of the bucket to create.\n\n" + "The bucket name must be unique, or an error will result.\n"; if (args.length < 1) { System.out.println(USAGE); System.exit(1); } String bucket_name = args[0]; System.out.format("\nCreating S3 bucket: %s\n", bucket_name); Bucket b = createBucket(bucket_name); if (b == null) { System.out.println("Error creating bucket!\n"); } else { System.out.println("Done!\n"); } } }

Sample Details

Service: s3

Last tested: 2018-11-06

Author: soo-aws

Type: full-example

On this page: