检查存储桶是否存在 - AWS SDK代码示例

AWS 文档 AWS SDK示例 GitHub 存储库中还有更多SDK示例

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

检查存储桶是否存在

以下代码示例显示了如何检查存储桶是否存在。

Java
SDK适用于 Java 2.x
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

您可以使用以下doesBucketExists方法来替代适用于 Java V1 的 Amazons3Client# doesBucketExist V2(字符串)方法。SDK

import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.amazon.awssdk.awscore.exception.AwsServiceException; import software.amazon.awssdk.http.HttpStatusCode; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.utils.Validate; public class DoesBucketExist { private static final Logger logger = LoggerFactory.getLogger(DoesBucketExist.class); public static void main(String[] args) { DoesBucketExist doesBucketExist = new DoesBucketExist(); final S3Client s3SyncClient = S3Client.builder().build(); final String bucketName = "amzn-s3-demo-bucket"; // Change to the bucket name that you want to check. boolean exists = doesBucketExist.doesBucketExist(bucketName, s3SyncClient); logger.info("Bucket exists: {}", exists); } /** * Checks if the specified bucket exists. Amazon S3 buckets are named in a global namespace; use this method to * determine if a specified bucket name already exists, and therefore can't be used to create a new bucket. * <p> * Internally this method uses the <a * href="https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/s3/S3Client.html#getBucketAcl(java.util.function.Consumer)">S3Client.getBucketAcl(String)</a> * operation to determine whether the bucket exists. * <p> * This method is equivalent to the AWS SDK for Java V1's <a * href="https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/s3/AmazonS3Client.html#doesBucketExistV2-java.lang.String-">AmazonS3Client#doesBucketExistV2(String)</a>. * * @param bucketName The name of the bucket to check. * @param s3SyncClient An <code>S3Client</code> instance. The method checks for the bucket in the AWS Region * configured on the instance. * @return The value true if the specified bucket exists in Amazon S3; the value false if there is no bucket in * Amazon S3 with that name. */ public boolean doesBucketExist(String bucketName, S3Client s3SyncClient) { try { Validate.notEmpty(bucketName, "The bucket name must not be null or an empty string.", ""); s3SyncClient.getBucketAcl(r -> r.bucket(bucketName)); return true; } catch (AwsServiceException ase) { // A redirect error or an AccessDenied exception means the bucket exists but it's not in this region // or we don't have permissions to it. if ((ase.statusCode() == HttpStatusCode.MOVED_PERMANENTLY) || "AccessDenied".equals(ase.awsErrorDetails().errorCode())) { return true; } if (ase.statusCode() == HttpStatusCode.NOT_FOUND) { return false; } throw ase; } } }
  • 有关API详细信息,请参阅 “AWS SDK for Java 2.x API参考 GetBucketAcl” 中的。