使用 Java 删除和还原 Blob 容器

本文介绍了如何使用适用于 Java 的 Azure 存储客户端库删除容器。 如果已启用容器软删除,则可以还原已删除的容器。

先决条件

  • 本文假设已经设置了项目来使用适用于 Java 的 Azure Blob 存储客户端库。 要了解有关设置项目的信息,包括包安装、添加 import 指令和创建授权客户端对象,请参阅开始使用 Azure 存储和 Java
  • 授权机制必须具有删除 blob 容器或还原软删除容器的权限。 若要了解详细信息,请参阅以下 REST API 操作的授权指南:

删除容器

若要在 Java 中删除容器,请使用 BlobServiceClient 类中的以下方法之一:

还可以使用 BlobContainerClient 类中的以下方法之一删除容器:

删除容器后,至少在 30 秒内无法使用相同的名称创建容器。 尝试使用相同的名称创建容器将会失败,并出现 HTTP 错误代码 409 (Conflict)。 针对容器或其包含的 Blob 执行任何其他操作将会失败,并出现 HTTP 错误代码 404 (Not Found)

下面的示例使用 BlobServiceClient 对象删除指定容器:

public void deleteContainer(BlobServiceClient blobServiceClient, String containerName) {
    // Delete the container using the service client
    blobServiceClient.deleteBlobContainer(containerName);
}

以下示例演示如何删除以指定的前缀开头的所有容器:

public void deleteContainersWithPrefix(BlobServiceClient blobServiceClient) {
    ListBlobContainersOptions options = new ListBlobContainersOptions()
            .setPrefix("container-");

    // Delete the container with the specified prefix using the service client
    for (BlobContainerItem containerItem : blobServiceClient.listBlobContainers(options, null)) {
        BlobContainerClient containerClient = blobServiceClient.getBlobContainerClient(containerItem.getName());
        containerClient.delete();
    }
}

还原软删除的容器

为存储帐户启用容器软删除后,可以在指定的保持期内恢复删除的容器及其内容。 若要详细了解容器软删除,请参阅启用和管理容器的软删除。 可以通过调用 BlobServiceClient 类的以下方法来还原软删除的容器:

以下示例查找已删除的容器,获取该已删除容器的版本,然后将该版本传递到 undeleteBlobContainer 方法以还原该容器。

public void restoreContainer(BlobServiceClient blobServiceClient) {
    ListBlobContainersOptions options = new ListBlobContainersOptions();
    options.getDetails().setRetrieveDeleted(true);

    // Delete the container with the specified prefix using the service client
    for (BlobContainerItem deletedContainerItem : blobServiceClient.listBlobContainers(options, null)) {
        BlobContainerClient containerClient = blobServiceClient
                .undeleteBlobContainer(deletedContainerItem.getName(), deletedContainerItem.getVersion());
    }
}

资源

若要详细了解如何使用适用于 Java 的 Azure Blob 存储客户端库删除容器,请参阅以下资源。

REST API 操作

Azure SDK for Java 包含基于 Azure REST API 而生成的库,允许你通过熟悉的 Java 范例与 REST API 操作进行交互。 用于删除或还原容器的客户端库方法使用以下 REST API 操作:

代码示例

客户端库资源

请参阅