Path: blob/master/code_examples/java_examples/S3Examples/CreateBucket.java
4084 views
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.1// SPDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-s3-developer-guide/blob/master/LICENSE-SAMPLECODE.)23import java.io.IOException;45import com.amazonaws.AmazonServiceException;6import com.amazonaws.SdkClientException;7import com.amazonaws.auth.profile.ProfileCredentialsProvider;8import com.amazonaws.services.s3.AmazonS3;9import com.amazonaws.services.s3.AmazonS3ClientBuilder;10import com.amazonaws.services.s3.model.CreateBucketRequest;11import com.amazonaws.services.s3.model.GetBucketLocationRequest;1213public class CreateBucket {1415public static void main(String[] args) throws IOException {16String clientRegion = "*** Client region ***";17String bucketName = "*** Bucket name ***";1819try {20AmazonS3 s3Client = AmazonS3ClientBuilder.standard()21.withCredentials(new ProfileCredentialsProvider())22.withRegion(clientRegion)23.build();2425if (!s3Client.doesBucketExistV2(bucketName)) {26// Because the CreateBucketRequest object doesn't specify a region, the27// bucket is created in the region specified in the client.28s3Client.createBucket(new CreateBucketRequest(bucketName));2930// Verify that the bucket was created by retrieving it and checking its location.31String bucketLocation = s3Client.getBucketLocation(new GetBucketLocationRequest(bucketName));32System.out.println("Bucket location: " + bucketLocation);33}34}35catch(AmazonServiceException e) {36// The call was transmitted successfully, but Amazon S3 couldn't process37// it and returned an error response.38e.printStackTrace();39}40catch(SdkClientException e) {41// Amazon S3 couldn't be contacted for a response, or the client42// couldn't parse the response from Amazon S3.43e.printStackTrace();44}45}46}474849