Todos os produtos
Search
Central de documentação

Object Storage Service:Criar um bucket (SDK Java V1)

Última atualização: Jul 03, 2026

Um bucket é um contêiner para armazenamento de objetos. Todos os objetos devem ser armazenados em um bucket. Este tópico descreve como criar um bucket.

Observações

  • Este tópico utiliza o endpoint público da região China (Hangzhou). Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para obter detalhes sobre as regiões e endpoints compatíveis, consulte Regiões e endpoints.

  • As credenciais de acesso neste tópico são obtidas de variáveis de ambiente. Para mais informações sobre como configurar credenciais de acesso, consulte Configurar credenciais de acesso.

  • Este tópico demonstra como criar uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como uso de domínio personalizado ou autenticação com credenciais do Security Token Service (STS), consulte Configuração do cliente.

Permissões

Por padrão, uma conta Alibaba Cloud tem permissões totais. Usuários RAM ou funções RAM vinculados a essa conta não possuem permissões iniciais. A conta Alibaba Cloud ou o administrador deve conceder permissões de operação por meio de políticas do RAM ou Bucket Policy.

API

Ação

Descrição

PutBucket

oss:PutBucket

Cria um bucket.

oss:PutBucketAcl

Necessária para modificar a ACL do bucket após a criação.

Código de exemplo

O código abaixo exemplifica a criação de um bucket chamado examplebucket.

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        // Set yourEndpoint to the Endpoint of the region where the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set Endpoint to https://oss-cn-hangzhou.aliyuncs.com.
        String endpoint = "yourEndpoint";
        // Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the bucket name.
        String bucketName = "examplebucket";
        // Specify the resource group ID. If you do not specify a resource group ID, the bucket is added to the default resource group.
        //String rsId = "rg-aek27tc****";
        // Specify the region where the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set Region to cn-hangzhou.
        String region = "cn-hangzhou";
        
        // Create an OSSClient instance.
        // After an OSSClient instance is no longer used, call the shutdown method to release resources.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // Create a bucket and enable the hierarchical namespace feature.
            CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName).withHnsStatus(HnsStatus.Enabled);
            // If you want to specify the storage class, ACL, and data redundancy type when you create a bucket, see the following code.
            // The following code provides an example of how to set the storage class to Standard.
            createBucketRequest.setStorageClass(StorageClass.Standard);
            // The default data redundancy type is LRS, which is specified as DataRedundancyType.LRS. If you want to set the data redundancy type to ZRS, set the value to DataRedundancyType.ZRS.
            createBucketRequest.setDataRedundancyType(DataRedundancyType.ZRS);
            // Set the ACL of the bucket to public-read. The default ACL is private.
            createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
            // When you create a bucket in a region that supports resource groups, you can assign the bucket to a resource group.
            //createBucketRequest.setResourceGroupId(rsId);

            // Create the bucket.
            ossClient.createBucket(createBucketRequest);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}

Referências

  • Para acessar o código de exemplo completo de criação de bucket, consulte o exemplo no GitHub.

  • Para mais informações sobre a operação da API de criação de bucket, consulte PutBucket.