List buckets (Java SDK V2)

Updated at:

List all buckets in the current account by calling the ListBuckets operation with OSS Java SDK V2.

Prerequisites

  • OSS Java SDK V2 is installed. If you use Maven, add the com.aliyun:alibabacloud-oss-v2 dependency to the pom.xml file.

  • Access credentials are configured by using environment variables. The sample code in this topic uses EnvironmentVariableCredentialsProvider to read credentials from the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables.

Permissions

An Alibaba Cloud account has full permissions by default. RAM users and RAM roles under the account have no permissions by default and must be granted permissions by the Alibaba Cloud account or an account administrator.

API

Action

Description

ListBuckets

oss:ListBuckets

Lists all buckets.

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.*;
import com.aliyun.sdk.service.oss2.paginator.ListBucketsIterable;

public class ListBucketsSample {
    public static void main(String[] args) throws Exception {
        String region = "cn-hangzhou";

        CredentialsProvider provider = new EnvironmentVariableCredentialsProvider();
        OSSClientBuilder clientBuilder = OSSClient.newBuilder()
                .credentialsProvider(provider)
                .region(region);

        try (OSSClient client = clientBuilder.build()) {

            ListBucketsIterable paginator = client.listBucketsPaginator(
                    ListBucketsRequest.newBuilder()
                            .build());

            for (ListBucketsResult result : paginator) {
                for (BucketSummary info : result.buckets()) {
                    System.out.printf("bucket: name:%s, region:%s, storageClass:%s%n",
                            info.name(), info.region(), info.storageClass());
                }
            }

        } catch (Exception e) {
            System.out.printf("error:%n%s", e);
        }
    }
}

References