Determine whether a bucket exists (Java SDK V2)
Determine whether a bucket exists by calling the GetBucketInfo operation with OSS Java SDK V2.
Prerequisites
OSS Java SDK V2 is installed. If you use Maven, add the
com.aliyun:alibabacloud-oss-v2dependency topom.xml.Access credentials are configured by using environment variables. The sample code in this topic uses
EnvironmentVariableCredentialsProviderto read credentials from theOSS_ACCESS_KEY_IDandOSS_ACCESS_KEY_SECRETenvironment variables.
Permissions
An Alibaba Cloud account has all permissions by default. RAM users and RAM roles under the account have no permissions by default. The Alibaba Cloud account or an account administrator must grant the required permissions.
API | Action | Description |
GetBucketInfo |
| Retrieves bucket information to determine whether a bucket exists. |
Sample code
import com.aliyun.sdk.service.oss2.OSSClient;
import com.aliyun.sdk.service.oss2.OSSClientBuilder;
import com.aliyun.sdk.service.oss2.credentials.CredentialsProvider;
import com.aliyun.sdk.service.oss2.credentials.EnvironmentVariableCredentialsProvider;
import com.aliyun.sdk.service.oss2.models.*;
public class BucketExistsSample {
public static void main(String[] args) throws Exception {
String region = "cn-hangzhou";
String bucket = "examplebucket";
CredentialsProvider provider = new EnvironmentVariableCredentialsProvider();
OSSClientBuilder clientBuilder = OSSClient.newBuilder()
.credentialsProvider(provider)
.region(region);
try (OSSClient client = clientBuilder.build()) {
GetBucketInfoResult result = client.getBucketInfo(GetBucketInfoRequest.newBuilder()
.bucket(bucket)
.build());
System.out.printf("Bucket '%s' exists. Location: %s%n",
result.bucketInfo().name(), result.bucketInfo().location());
} catch (Exception e) {
System.out.printf("Bucket may not exist or access denied: %s%n", e.getMessage());
}
}
}
References
For the synchronous sample code, see GetBucketInfo.java.
For the asynchronous sample code, see GetBucketInfoAsync.java.