如何确定 Azure 中容器中所有 blob 的 Blob 类型?

How to determine the Blob type of all the blobs in a container in Azure?

我知道如何列出容器中的所有 blob,但我还需要知道 blob 的类型。现在我正在盲目地使用 class CloudBlockBlob 因为我得到一个错误作为 (com.microsoft.azure.storage.StorageException: 不正确的 Blob 类型,请使用正确的 Blob 类型来访问服务器上的 blob。预期 BLOCK_BLOB,实际 PAGE_BLOB.) 列表中有一个 PageBlob 类型。有没有办法确定 Blob 的类型?

我的代码是这样的:

public static void getContainerFiles(CloudStorageAccount storageAccount, String containerName) {
    String fName = "";
    Date lstMdfdDate = null;
    try
    {
        // Define the connection-string with your values
        String storageConnectionString = "DefaultEndpointsProtocol=https;" +"AccountName=" + storageName + ";AccountKey="+key;
        // Retrieve storage account from connection-string.
        storageAccount = CloudStorageAccount.parse(storageConnectionString);
        // Create the blob client.
        CloudBlobClient blobClient = storageAccount.createCloudBlobClient();

        // Retrieve reference to a previously created container.
        CloudBlobContainer container = blobClient.getContainerReference(containerName);

        StorageCredentials cred = storageAccount.getCredentials();
        System.out.println(">>> AccountName: " + cred.getAccountName());
        System.out.println("Listing files of \"" + containerName + "\" container");
        // Loop over template directory within the container to get the template file names.
        CloudBlockBlob blob = null; 
        for (ListBlobItem blobItem : container.listBlobs()) {
          fName = getFileNameFromBlobURI(blobItem.getUri(), containerName);
            blob = container.getBlockBlobReference(fName);
            blob.downloadAttributes();
            lstMdfdDate = blob.getProperties().getLastModified();
        }
    } catch (Exception e) {
    }
}

private static String getFileNameFromBlobURI(URI uri, String containerName)
{
    String urlStr = uri.toString();
    String keyword = "/"+containerName+"/";
    int index = urlStr.indexOf(keyword) + keyword.length();
    String filePath = urlStr.substring(index);
    return filePath;
}

您可以检查 blobItem 的类型。例如,类似于以下内容:

if (CloudBlockBlob.class == blobItem.getClass()) {
    blob = (CloudBlockBlob)blobItem;
}
else if (CloudPageBlob.class == blobItem.getClass()) {
    blob = (CloudPageBlob)blobItem;
}
else if (CloudAppendBlob.class == blobItem.getClass()) {
    blob = (CloudAppendBlob)blobItem;
}

如果您使用的是旧版本的库,则可以省略 CloudAppendBlob 块,但我建议您进行更新以获取最新的错误修复以及该功能。另请注意,这消除了解析名称的需要。

添加另一种检查类型@Emily 的答案的方法,您可以只使用“is”运算符。

if (blobItem is CloudBlockBlob)
{
 ...
}
else if (blobItem is CloudPageBlob)
{
 ...
}
else if (blobItem is CloudAppendBlob)
{
 ...
}

与转换相比,这看起来更易读,速度更快;)