Checking for existence of S3 bucket - Java AWS SDK 2

0

Hi, what is the best way to check for the existence of an S3 bucket using the Java AWS SDK 2? I am not seeing relevant code examples for this. Thanks.

質問済み 4ヶ月前462ビュー
3回答
0
承認された回答

Hi, To check for the existence of an S3 bucket using the Java AWS SDK 2, you can use the HeadBucketRequest class within the com.amazonaws.services.s3.AmazonS3 package. Here's an example:

AmazonS3 s3Client = AmazonS3Client.create();
HeadBucketRequest headBucketRequest = new HeadBucketRequest("your-bucket-name");
s3Client.headBucket(headBucketRequest);

If the bucket exists, this code will return a Bucket object. If not, it will throw a NoSuchBucketException. More information can be found in the official AWS SDK for Java 2 Developer Guide: https://docs.aws.amazon.com/sdk-for-java/v2/developer-guide/examples-s3-buckets.html

profile picture
回答済み 4ヶ月前
0

Hi,

For your need, check out: https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/examples-s3-buckets.html

They provide a code example:

import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.AmazonS3Exception;
import com.amazonaws.services.s3.model.Bucket;

import java.util.List;

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;

Best,

Didier

profile pictureAWS
エキスパート
回答済み 4ヶ月前
  • Thanks, but this is version 1, I am looking for example from version 2.

0

Depending on what you want to archive you can either use headBucket method of S3Client and check for NoSuchBucketException or if you just want to ensure it is created you may even try createBucket and catch exception:

 * @throws BucketAlreadyExistsException
 *         The requested bucket name is not available. The bucket namespace is shared by all users of the system.
 *         Select a different name and try again.
 * @throws BucketAlreadyOwnedByYouException
 *         The bucket you tried to create already exists, and you own it. Amazon S3 returns this error in all AWS
 *         Regions except in the North Virginia Region. For legacy compatibility, if you re-create an existing
 *         bucket that you already own in the North Virginia Region, Amazon S3 returns 200 OK and resets the bucket
 *         access control lists (ACLs).
Joerg
回答済み 3ヶ月前

ログインしていません。 ログイン 回答を投稿する。

優れた回答とは、質問に明確に答え、建設的なフィードバックを提供し、質問者の専門分野におけるスキルの向上を促すものです。

質問に答えるためのガイドライン

関連するコンテンツ