[英]How to check if bucket already exists in AWS S3
How can I check if the bucket already exists in my Aws S3 account using Java SDK?如何使用 Java SDK 检查存储桶是否已存在于我的 Aws S3 账户中?
Using below code使用下面的代码
AmazonS3ClientBuilder.defaultClient().doesBucketExistV2(bucketName);
Checks global existence of bucket and returns true if a bucket with this name exists globally even if I am not the owner of this bucket or I don't have access to that bucket.检查存储桶的全局存在,如果具有此名称的存储桶全局存在,则返回 true,即使我不是该存储桶的所有者或者我无权访问该存储桶。
I understand the intent for making this method this way so that It allows us to determine the availability of bucket name but this is not what I need.我理解以这种方式制作此方法的意图,以便它允许我们确定存储桶名称的可用性,但这不是我所需要的。 Of course, it will throw exception that I don't have access to it later, but it returns stating that bucket with this name exists.
当然,它会抛出我以后无法访问它的异常,但它会返回说明具有此名称的存储桶存在。
I want to check if the bucket with the given name exists in my S3 account so that I can perform operations on it.我想检查我的 S3 帐户中是否存在具有给定名称的存储桶,以便我可以对其执行操作。
One possible solution for it can be to list
all the buckets and search for my bucket in that returned list which I feel is not a good performance-wise (correct me if I am wrong) as there can be hundreds of thousands of buckets and searching in them is not efficient.一种可能的解决方案是
list
所有存储桶并在返回的列表中搜索我的存储桶,我认为这不是一个好的性能(如果我错了,请纠正我),因为可能有数十万个存储桶和搜索在他们中效率不高。
How can I determine if a bucket exists in my S3 account not checking global existence ?如何确定我的 S3 帐户中是否存在未检查全局存在的存储桶?
as mentioned in the comments headBucket
does the job.正如评论中提到的
headBucket
完成了这项工作。
HeadBucketRequest headBucketRequest = HeadBucketRequest.builder()
.bucket(bucketName)
.build();
try {
s3Client.headBucket(headBucketRequest);
return true;
} catch (NoSuchBucketException e) {
return false;
}
SDK 1.x does not have a HeadBucketRequest
builder nor a NoSuchBucketException
. SDK 1.x 没有
HeadBucketRequest
构建器,也没有NoSuchBucketException
。
In case anyone is looking for the answer using AWS SDK for Java 1.x , this works:如果有人正在使用AWS SDK 为 Java 1.x寻找答案,则此方法有效:
private boolean checkAccessToBucket(final String bucketName) {
try {
final HeadBucketRequest request = new HeadBucketRequest(bucketName);
s3Client.headBucket(request);
return true;
} catch (AmazonServiceException ex) {
if (ex.getStatusCode() == 404 | ex.getStatusCode() == 403 || ex.getStatusCode() == 301) {
return false;
}
throw ex;
} catch (Exception ex) {
LOGGER.error("Cannot check access", ex);
throw ex;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.