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